<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">
          <BTabs>
            <BTab title="دسته بندی">
              <div class="form-group mt-2">
                <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
                    type="button"
                    class="btn btn-secondary"
                    data-bs-dismiss="modal"
                    id="close"
                >
                  بستن
                </button>

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

            </BTab>

            <BTab title="ترجمه ها">
              <form @submit.prevent="editAttribute" class="mt-4">

                <BButton
                    :disabled="!findLocaleTranslation"
                    :loading="loadingDelete"
                    @click="handlerRemoveTranslation"
                    class="btn btn-sm rounded btn-danger d-block"
                    style="margin-right: auto"
                >
                  حذف ترجمه {{ findLocaleTranslation }}
                </BButton>

                <BRow class="g-3">
                  <!-- Brand Title -->
                  <BCol lg="6">
                    <div class="form-group">
                      <label class="form-label">عنوان ویژگی</label>

                      <input
                          v-model="localTitle"
                          @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="انتخاب کنید"
                          @change="handlerChangeLocale"
                      >
                        <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"
                  >
                    بستن
                  </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"
                    />
                    ذخیره
                  </button>
                </div>
              </form>
            </BTab>
          </BTabs>
        </div>
      </div>
    </div>
  </div>
</template>

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

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

export default {
  components: {BTabs},
  props: {
    attributeValues: {
      type: Array,
      Required: true,
    },
    code: {
      type: String,
      Required: true,
    },
    title: {
      type: String,
      Required: true,
    },
    id: {
      type: String,
      Required: true,
    },
    attrRow: {
      type: Object,
      required: true,
    },
  },
  setup(props, { emit }) {
    const localTitle = ref();
    const localColorCode = ref();
    const errors = ref({});
    const loading = ref(false);
    const categoryId = ref(null);
    const categories = ref([]);
    const locale = ref('fa');
    const loadingDelete = ref(false);
    const loadingAttr = ref(false);

    const attrRowModel = computed({
      get: () => props.attrRow,
      set: (newValue) => emit('update:categoryRow', newValue)
    });

    watch(
        () => props.attrRow,
        (newVal) => {
          localTitle.value = newVal?.translation?.title

          locale.value = newVal?.translation?.locale

          categoryId.value = newVal?.category?.id
        }
    )

    const findLocaleTranslation = computed(() => {
      const foundTranslation = attrRowModel.value?.translations?.find(
          item => item?.locale === locale.value
      );

      if (foundTranslation) {
        switch (foundTranslation?.locale) {
          case "en":
            return "انگلیسی";
          case "fa":
            return "فارسی";
          case "ar":
            return "عربی";
          default:
            return null;
        }
      }

      return null;
    });

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

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

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

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

      try {
        loading.value = true;

        const params = { title: localTitle.value, locale: locale.value };

        const existingTranslation = attrRowModel.value?.translations?.find(
            t => t.locale === locale.value
        );

        const { data } = existingTranslation
            ? await ApiServiece.put(
                `admin/attributes/${attrRowModel.value?.id}/translations/${existingTranslation?.id}`,
                params,
                {
                  headers: {
                    Authorization: `Bearer ${localStorage.getItem("token")}`,
                  },
                }
            )
            : await ApiServiece.post(
                `admin/attributes/${attrRowModel.value?.id}/translations`,
                params,
                {
                  headers: {
                    Authorization: `Bearer ${localStorage.getItem("token")}`,
                  },
                }
            );

        if (data?.success) {
          const updatedCategory = props.attrRow;

          if (existingTranslation) {
            updatedCategory.translations = data?.data?.translations || [];
          } else {
            updatedCategory.translations = [
              ...(updatedCategory.translations || []),
              ...(data?.data?.translations || [])
            ];
          }

          attrRowModel.value = updatedCategory;

          toast.success(data?.message)

          emit("attribute-updated");
        }

      } catch (error) {
        console.log(error,'error error');
        toast.error(`${error?.response?.data?.message}`, {
          position: "top-right",
          autoClose: 1000,
        });
      } finally {
        loading.value = false;
      }
    };

    const handlerRemoveTranslation = async () => {
      const findLocale = attrRowModel.value?.translations?.find(item => item?.locale === locale.value);

      if (findLocale) {
        try {
          loadingDelete.value = true;

          const { data: { success, message, data } } = await ApiServiece.delete(
              `admin/attributes/${attrRowModel.value?.id}/translations/${findLocale?.id}`
          )

          if (success) {
            const updatedCategory = props.attrRow;

            if (findLocale) {
              updatedCategory.translations = data?.translations || [];
            } else {
              updatedCategory.translations = [
                ...(updatedCategory.translations || []),
                ...(data?.translations || [])
              ];
            }

            attrRowModel.value = updatedCategory;

            localTitle.value = null

            toast.success(message)
          }
        } catch (e) {
          toast.error(e?.response?.data?.message)
        }finally {
          loadingDelete.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)
      }
    }

    const handlerChangeLocale = (e) => {
      const findLocale = attrRowModel.value?.translations?.find(item => item?.locale === e.target.value);

      if (findLocale) {
        localTitle.value = findLocale?.title
      } else {
        localTitle.value = undefined
      }
    }

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

        const params = {
          category_id: categoryId.value,
        }

        const { data: { success, message } } = await ApiServiece.put(`admin/attributes/${props.attrRow?.id}`, params)

        if (success) {
          toast.success(message)

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

    getAttributes()

    return {
      errors,
      loading,
      clearError,
      editAttribute,
      localTitle,
      localColorCode,
      categoryId,
      getAttributes,
      categories,
      attrRowModel,
      handlerChangeLocale,
      locale,
      findLocaleTranslation,
      handlerRemoveTranslation,
      loadingDelete,
      handlerSubmitAttribute,
      loadingAttr,
    };
  },
};
</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>
