<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">
                    <select
                      class="form-control selector"
                      @change="clearError(`localCat`)"
                      v-model="localCatId"
                      :class="{ 'is-invalid': errors.localCat }"
                      placeholder="انتخاب دسته"
                    >
                      <option
                        v-for="cat in localCat"
                        :key="cat.id"
                        :value="cat.id"
                      >
                        {{ cat.title }}
                      </option>
                    </select>
                  </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, toRef, watch } from "vue";

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

export default {
  props: {
    title: {
      type: String,
      Required: true,
    },
    catId: {
      type: String,
      Required: true,
    },
    id: {
      type: String,
      Required: true,
    },
    cats: {
      type: Array,
      Required: true,
    },
  },
  setup(props, { emit }) {
    const localCat = toRef(props.cats);
    const localTitle = toRef(props.title);
    const localCatId = toRef(props.catId);
    const localId = toRef(props.id);
    const errors = ref({});
    const loading = 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.catId,
      (newVal) => (localCatId.value = newVal)
    );

    const validateForm = () => {
      errors.value = {};
      if (!localTitle.value)
        errors.value.localTitle = "وارد کردن عنوان مشخصه ضروری می باشد";
      if (!localCat.value) errors.value.localCat = "انتخاب دسته ضروری می باشد";
      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("close").click();
            emit("attribute-updated");
          }, 500);
        })
        .catch((error) => {
          console.error(error);
          toast.error("!ویرایش مشخصه با مشکل مواجه شد", {
            position: "top-right",
            autoClose: 1000,
          });
        })
        .finally(() => {
          loading.value = false;
        });
    };

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