<template>
  <div
    class="modal fade"
    id="editAttribute"
    tabindex="-1"
    role="dialog"
    aria-labelledby="exampleModalLabel"
    aria-hidden="true"
  >
    <div class="modal-dialog modal-sm" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">ویرایش رنگ</h5>
          <button
            type="button"
            class="btn-close"
            data-bs-dismiss="modal"
            aria-label="Close"
          ></button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="editAttribute">
            <BRow class="g-3">
              <!-- Brand Title -->
              <BCol lg="6">
                <div class="form-group">
                  <label class="form-label">نام رنگ</label>

                  <input
                    v-model="localColorName"
                    @input="clearError('localColorName')"
                    type="text"
                    class="form-control"
                    placeholder="نام رنگ"
                    :class="{ 'is-invalid': errors.colorName }"
                  />
                  <small v-if="errors.localColorName" class="text-danger">
                    {{ errors.localColorName }}
                  </small>
                </div>
              </BCol>

              <BCol lg="6">
                <div class="form-group">
                  <label class="form-label">انتخاب رنگ</label>
                  <div class="color-picker-wrapper">
                    <input
                      v-model="localColorCode"
                      @input="clearError('localColorCode')"
                      type="color"
                      class="form-control color-picker"
                      :class="{ 'is-invalid': errors.localColorCode }"
                    />
                    <span
                      v-if="colorCode"
                      class="color-display"
                      :style="{ backgroundColor: localColorCode }"
                    ></span>
                  </div>
                  <span> {{ localColorCode }}</span>

                  <small v-if="errors.localColorCode" class="text-danger">
                    {{ errors.localColorCode }}
                  </small>
                </div>
              </BCol>
            </BRow>

            <!-- Submit Buttons -->
            <div
              class="d-flex justify-content-end gap-2"
              style="margin-top: 20px"
            >
              <button
                type="button"
                class="btn btn-secondary"
                data-bs-dismiss="modal"
                id="closeAttributeModal"
              >
                بستن
              </button>
              <button type="submit" class="btn btn-primary" :disabled="loading">
                <span
                  v-if="loading"
                  class="spinner-border spinner-border-sm"
                  role="status"
                  aria-hidden="true"
                ></span>
                ذخیره
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, toRef, watch } from "vue";

import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import ApiServiece from "@/services/ApiService";

export default {
  props: {
    attributeValues: {
      type: Array,
      Required: true,
    },
    code: {
      type: String,
      Required: true,
    },
    title: {
      type: String,
      Required: true,
    },
    id: {
      type: String,
      Required: true,
    },
  },
  setup(props, { emit }) {
    const localColorName = ref();
    const localColorCode = ref();
    const localId = toRef(props.id);
    const localAttributeValues = toRef(props.attributeValues);
    const errors = ref({});
    const loading = ref(false);

    watch(
      () => props.attributeValues,
      (newVal) => (localAttributeValues.value = newVal)
    );

    watch(
      () => props.code,
      (newVal) => (localColorCode.value = newVal)
    );

    watch(
      () => props.title,
      (newVal) => (localColorName.value = newVal)
    );

    watch(
      () => props.id,
      (newVal) => (localId.value = newVal)
    );

    const validateForm = () => {
      errors.value = {};
      if (!localColorName.value)
        errors.value.colorName = "وارد کردن نام رنگ ضروری می باشد";
      if (!localColorCode.value)
        errors.value.colorCode = "انتخاب رنگ ضروری می باشد";

      return Object.keys(errors.value).length === 0;
    };

    const clearError = (field) => {
      errors.value[field] = "";
    };

    const editAttribute = () => {
      if (!validateForm()) return;
      loading.value = true;

      const formData = new FormData();
      console.log(localAttributeValues.value);
      formData.append("title", localColorName.value);
      formData.append("code", localColorCode.value);
      formData.append("attribute_id", localAttributeValues.value[0].id);

      ApiServiece.put(`admin/attribute-values/${localId.value}`, formData)
        .then((resp) => {
          console.log(resp);
          toast.success("!ویژگی با موفقیت ویرایش شد", {
            position: "top-right",
            autoClose: 1000,
          });
        })
        .then(() => {
          setTimeout(() => {
            document.getElementById("closeAttributeModal").click();
            emit("attribute-updated");
          }, 500);
        })
        .catch((error) => {
          console.error(error);
          toast.success("!مشکلی در ویرایش ویژگی پیش آمد", {
            position: "top-right",
            autoClose: 1000,
          });
        })
        .finally(() => {
          loading.value = false;
        });
    };

    return {
      errors,
      loading,
      clearError,
      editAttribute,
      localColorName,
      localColorCode,
    };
  },
};
</script>

<style scoped>
.modal-dialog {
  max-width: 50%;
}

.modal-content {
  padding: 20px;
}

.modal-body {
  padding: 20px;
  padding: 1rem 1.5rem;
}

.form-group {
  margin-bottom: 1rem;
}

.input-group {
  margin-top: 0.5rem;
}

.modal-dialog {
  max-width: 50%;
}

.modal-content {
  padding: 1.5rem;
}

.modal-header {
  border-bottom: 1px solid #dee2e6;
  padding-bottom: 1rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.input-group {
  margin-top: 0.5rem;
}

.Image-Preview {
  min-width: 100px;
  max-height: 100px;
  max-width: 100px;
  object-fit: cover;
  border-radius: 8px;
  border: 1px solid #ddd;
}
.delete-btn {
  display: flex;
  align-items: center;
  padding: 3px;
  font-size: 10px;
  background-color: #e74c3c;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease, transform 0.2s ease;
  gap: 8px; /* Space between icon and text */
  margin-right: 100px;
}

.delete-btn:hover {
  background-color: #c0392b;
  transform: scale(1.05);
}

.delete-btn:active {
  background-color: #a93226;
}

.delete-btn:focus {
  outline: none;
}
.color-picker-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.color-picker {
  width: 300px;
  height: 45px;
  padding: 0;
  border-radius: 10px;
  border: none;
  cursor: pointer;
}

.color-display {
  width: 30px;
  height: 30px;
  margin-left: 10px;
  border-radius: 50%;
  border: 2px solid #ccc;
  display: inline-block;
}
</style>
