<template>
  <div
    class="modal fade"
    id="addAttribute"
    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">
          <Steppy
              v-model:step="step"
              :tabs="[
                 { title: 'ثبت دسته بندی', isValid: true },
                 { title: 'ترجمه ها', isValid: true },
              ]"
              backText="قبلی"
              nextText="بعدی"
              doneText="ذخیره"
              primaryColor1="#04A9F5"
              circleSize="45"
          >
            <template #1>
              <div class="form-group">
                <label class="form-label">دسته بندی</label>
                <select
                    v-model="categoryId"
                    class="form-control"
                    placeholder="دسته بندی انتخاب کنید"
                >
                  <option
                      v-for="category in categories"
                      :key="category?.id"
                      :value="category?.id"
                  >
                    {{ category?.translation?.title ?? 'بدون نام' }}
                  </option>
                </select>
              </div>

              <!-- Submit Buttons -->
              <div
                  class="d-flex justify-content-end gap-2"
                  style="margin-top: 20px"
              >
                <button
                    class="btn btn-secondary"
                    data-bs-dismiss="modal"
                    id="close"
                    @click="step = 1"
                >
                  بستن
                </button>

                <button @click="handlerSubmitCategory" class="btn btn-primary" :disabled="loading">
                  <span
                      v-if="loading"
                      class="spinner-border spinner-border-sm"
                      role="status"
                      aria-hidden="true"
                  />
                  ذخیره
                </button>
              </div>
            </template>

            <template #2>
              <form @submit.prevent="addAttribute">
                <BRow class="g-3">
                  <!-- Brand Title -->
                  <BCol lg="6">
                    <div class="form-group">
                      <label class="form-label">عنوان ویژگی</label>

                      <input
                          v-model="attrName"
                          @input="clearError('attrName')"
                          type="text"
                          class="form-control"
                          placeholder="عنوان ویژگی"
                          :class="{ 'is-invalid': errors.attrName }"
                      />
                      <small v-if="errors.attrName" class="text-danger">
                        {{ errors.attrName }}
                      </small>
                    </div>
                  </BCol>

                  <BCol lg="6">
                    <div class="form-group">
                      <label class="form-label">انتخاب زبان</label>
                      <select
                          v-model="locale"
                          class="form-control"
                          placeholder="انتخاب کنید"
                      >
                        <option
                            key="fa"
                            value="fa"
                        >
                          فارسی
                        </option>
                        <option
                            key="en"
                            value="en"
                        >
                          انگلیسی
                        </option>
                        <option
                            key="ar"
                            value="ar"
                        >
                          عربی
                        </option>
                      </select>
                    </div>
                  </BCol>
                </BRow>

                <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"
                      @click="step = 1"
                  >
                    بستن
                  </button>

                  <button type="submit" class="btn btn-primary" :disabled="loadingAttr">
                    <span
                        v-if="loadingAttr"
                        class="spinner-border spinner-border-sm"
                        role="status"
                        aria-hidden="true"
                    />
                    ذخیره
                  </button>
                </div>
              </form>
            </template>
          </Steppy>
        </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";
import {Steppy} from "vue3-steppy";

export default {
  components: {Steppy},
  props: {
    attributeValues: {
      type: Array,
      Required: true,
    },
  },
  setup(props, { emit }) {
    const attrName = ref();
    const colorCode = ref();
    const localAttributeValues = toRef(props.attributeValues);
    const errors = ref({});
    const loading = ref(false);
    const loadingAttr = ref(false);
    const categories = ref([]);
    const categoryId = ref(null);
    const categoryResponse = ref(null);
    const step = ref(1);
    const locale = ref('fa');

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

    const validateForm = () => {
      errors.value = {};
      // if (!attrName.value)
      //   errors.value.attrName = "وارد کردن نام ویژگی ضروری می باشد";
      if (!categoryId.value) errors.value.categoryId = "انتخاب دسته بندی ضروری می باشد";

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

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

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

      loading.value = true;

      const params = {
        category_id: categoryId.value,
      }

      ApiServiece.post(`admin/attributes`, params)
        .then(({ data }) => {
          toast.success(data?.message, {
            position: "top-right",
            autoClose: 1000,
          });
          categoryResponse.value = data?.data?.id;
          step.value++
        })
        .catch((error) => {
          toast.error(`${error.response.data.message}`, {
            position: "top-right",
            autoClose: 1000,
          });
        })
        .finally(() => {
          loading.value = false;
        });
    };

    const addAttribute = async () => {
      try {
        loadingAttr.value = true;

        const params = {
          title: attrName.value,
          locale: locale.value,
        }

        const { data: { success, message } } = await ApiServiece.post(`admin/attributes/${categoryResponse.value}/translations`, params)

        if (success) {
          toast.success(message)
          //document.getElementById("close").click();

          attrName.value = undefined;

          emit("attribute-updated");
        }
      } catch (e) {
        toast.error(e?.response?.data?.message)
      } finally {
        loadingAttr.value = false;
      }
    }

    const getAttributes = async () => {
      try {
        const { data: { success, data } } = await ApiServiece.get(`admin/categories`)

        if (success) {
          categories.value = data;
        }
      } catch (e) {
        toast.error(e?.response?.data?.message)
      }
    }


    getAttributes()

    return {
      errors,
      loading,
      clearError,
      handlerSubmitCategory,
      attrName,
      colorCode,
      getAttributes,
      categories,
      loadingAttr,
      categoryId,
      step,
      locale,
      addAttribute
    };
  },
};
</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>
