<template>
  <div
    class="modal fade"
    id="editIdentity"
    tabindex="-1"
    role="dialog"
    aria-labelledby="exampleModalLabel"
    aria-hidden="false"
  >
    <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="editIdentity">
            <BRow class="g-3">
              <!-- Brand Title -->
              <BCol lg="6">
                <div class="form-group">
                  <label class="form-label">عنوان مشخصه</label>

                  <input
                    v-model="localTitle"
                    @input="clearError('localTitle')"
                    type="text"
                    class="form-control"
                    placeholder="عنوان مشخصه"
                    :class="{ 'is-invalid': errors.localTitle }"
                  />
                  <small v-if="errors.localTitle" class="text-danger">
                    {{ errors.localTitle }}
                  </small>
                </div>
              </BCol>

              <BCol lg="6">
                <div class="form-group">
                  <label class="form-label">انتخاب دسته</label>

                  <div class="color-picker-wrapper">
                    <VueSelect
                      style="--vs-min-height: 48px; --vs-border-radius: 8px"
                      v-model="localCatId"
                      :options="formattedCategories"
                      :isLoading="categorySelectorLoader"
                      label="label"
                      :reduce="(option) => option.value"
                      placeholder="دسته ای را انتخاب کنید"
                      @search="handleSearch"
                    />
                  </div>
                  <small v-if="errors.selectedCat" class="text-danger">
                    {{ errors.selectedCat }}
                  </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="closeIdentityModal"
              >
                بستن
              </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, computed } from "vue";
import VueSelect from "vue3-select-component";
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import ApiServiece from "@/services/ApiService";

export default {
  props: {
    title: {
      type: String,
      Required: true,
    },
    cat: {
      type: Object,
      Required: true,
    },
    id: {
      type: String,
      Required: true,
    },
    cats: {
      type: Array,
      Required: true,
    },
  },
  components: {
    VueSelect,
  },
  setup(props, { emit }) {
    const localCat = toRef(props.cats);
    const localTitle = toRef(props.title);
    const localCatId = toRef(props.cat);
    const localId = toRef(props.id);
    const errors = ref({});
    const loading = ref(false);
    const categorySelectorLoader = ref(false);

    watch(
      () => props.cats,
      (newVal) => {
        localCat.value = newVal
      }
    );

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

    watch(
      () => props.id,
      (newVal) => {
        localId.value = newVal
      }
    );
    
    watch(
      () => props.cat,
      (newVal) => {
        localCatId.value = newVal?.id;
        localCat.value = [{ title: newVal?.title, id: newVal?.id  }];
      },{ immediate: true });

    const handleSearch = async (searchTerm) => {
      if (searchTerm?.length < 3) return;
      categorySelectorLoader.value = true;
      try {
        const response = await ApiServiece.get(
            `admin/categories?title=${searchTerm}`
        );
        localCat.value = response.data.data;
        categorySelectorLoader.value = false;
      } catch (error) {
        categorySelectorLoader.value = false;
        localCat.value = [];
      }
    };

    const formattedCategories = computed(() =>
      Array.isArray(localCat.value)
        ? localCat.value.map((category) => ({
            value: category.id,
            label: category.title || '',
          }))
        : []
    );

    const validateForm = () => {
      errors.value = {};
      if (!localTitle.value)
        errors.value.localTitle = "وارد کردن عنوان مشخصه ضروری می باشد";
      return Object.keys(errors.value).length === 0;
    };

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

    const editIdentity = () => {
      if (!validateForm()) {
        toast.error("لطفا فیلد های لازم را وارد نمایید", {
          position: "top-right",
          autoClose: 1000,
        });
        return;
      }
      loading.value = true;
      const formData = new FormData();

      formData.append("category_id", localCatId.value ?? '' +
          '' +
          '');

      formData.append("title", localTitle.value);

      ApiServiece.put(`admin/attributes/${localId.value}`, formData)
        .then((resp) => {
          console.log(resp);
          toast.success("!مشخصه با موفقیت ویرایش شد", {
            position: "top-right",
            autoClose: 1000,
          });
        })
        .then(() => {
          setTimeout(() => {
            document.getElementById("closeIdentityModal").click();
            emit("identity-updated");
          }, 500);
        })
        .catch((error) => {
          toast.error(`${error.response.data.message}`, {
            position: "top-right",
            autoClose: 1000,
          });
        })
        .finally(() => {
          loading.value = false;
        });
    };

    return {
      errors,
      loading,
      clearError,
      editIdentity,
      localCat,
      localTitle,
      localId,
      localCatId,
      formattedCategories,
      categorySelectorLoader,
      handleSearch,
    };
  },
};
</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>
