<template>
  <div
    class="modal fade"
    id="addIdentity"
    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="addIdentity">
            <BRow class="g-3">
              <!-- Brand Title -->
              <BCol lg="12">
                <div class="form-group">
                  <label class="form-label">عنوان مشخصه</label>

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

              <BCol v-if="!categoryId" lg="12">
                <div class="form-group">
                  <label class="form-label">انتخاب دسته</label>

                  <div class="color-picker-wrapper">
                    <VueSelect
                      style="--vs-min-height: 48px; --vs-border-radius: 8px"
                      :isLoading="categorySelectorLoader"
                      v-model="selectedCat"
                      :options="formattedCategories"
                      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="close"
              >
                بستن
              </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, computed } from "vue";
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import ApiServiece from "@/services/ApiService";
import VueSelect from "vue3-select-component";

export default {

  props: {
    categoryId: {
      type: Number,
      required: true,
    }
  },

  components: {
    VueSelect
  },

  setup(props, { emit }) {
    const selectedCat = ref();
    const title = ref();
    const errors = ref({});
    const loading = ref(false);
    const categories = ref([]);
    const categorySelectorLoader = ref(false);

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

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

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

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

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

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

      const formData = new FormData();
      if (props.categoryId || selectedCat.value) {
        formData.append("category_id", props.categoryId || selectedCat.value);
      }
      formData.append("title", title.value);

      ApiServiece.post(`admin/attributes`, formData)
        .then((resp) => {
          console.log(resp);
          toast.success("!مشخصه با موفقیت اضافه شد", {
            position: "top-right",
            autoClose: 1000,
          });

          // **Reset form fields**
          title.value = "";
          selectedCat.value = null;
        })
        .then(() => {
          setTimeout(() => {
            document.getElementById("close").click();
            emit("identity-updated");
            selectedCat.value = "";
            title.value = "";
          }, 500);
        })
        .catch((error) => {
          console.error(error);
          toast.error(`${error.response.data.message}`, {
            position: "top-right",
            autoClose: 1000,
          });
        })
        .finally(() => {
          loading.value = false;
        });
    };

    return {
      errors,
      loading,
      clearError,
      addIdentity,
      formattedCategories,
      categorySelectorLoader,
      handleSearch,
      title,
      selectedCat,
    };
  },
};
</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>
