<template>
  <div
      class="modal fade"
      id="editCat"
      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="دسته بندی">
              <BRow>
                <BCol lg="12">
                  <div class="form-group mt-3">
                    <label class="form-label">انتخاب پدر</label>
                    <select
                        v-model="selectedPaernt"
                        class="form-control"
                        placeholder="انتخاب کنید"
                    >
                      <option :value="''">
                        ندارد
                      </option>
                      <option
                          v-for="parent in localParents"
                          :key="parent.id"
                          :value="parent.id"
                      >
                        {{ parent?.translation?.title ?? 'بدون نام' }}
                      </option>
                    </select>
                  </div>

                  <button
                      :disabled="loadingStep"
                      @click="handlerSubmitCategory"
                      class="btn rounded btn-primary w-auto"
                  >
                    <span
                        v-if="loadingStep"
                        class="spinner-border spinner-border-sm"
                        role="status"
                    />
                    ذخیره
                  </button>
                </BCol>
              </BRow>
            </BTab>
            <BTab title="ترجمه ها">
              <form @submit.prevent="editCat" 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">
                  <BCol lg="6">
                    <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 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>

                <BRow class="g-3">
                  <BCol lg="12">
                    <div class="form-group">
                      <label class="form-label">توضیحات دسته</label>
                      <textarea
                          v-model="description"
                          @input="clearError('description')"
                          type="text"
                          class="form-control"
                          placeholder="توضیحات دسته"
                          :class="{ 'is-invalid': errors.description }"
                      ></textarea>
                      <small v-if="errors.description" class="text-danger">
                        {{ errors.description }}
                      </small>
                    </div>
                  </BCol>
                </BRow>

                <!-- Submit Buttons -->
                <div
                    class="d-flex justify-content-between gap-2"
                    style="margin-top: 20px"
                >
                  <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>
            </BTab>
          </BTabs>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, toRef, watch, computed } from "vue";
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import ApiServiece from "@/services/ApiService";
import { useModal } from '@/utils/useModal';
import {BButton} from "bootstrap-vue-next";

export default {
  components: {BButton},
  props: {
    parents: {
      type: Array,
      Required: true,
    },
    categoryRow: {
      type: Object,
      Required: true,
    },
  },

  setup(props, { emit }) {
    const selectedPaernt = ref();
    const localParents = toRef(props.parents);
    const image = ref(null);
    const description = ref();
    const title = ref();
    const errors = ref({});
    const loading = ref(false);
    const loadingStep = ref(false);
    const loadingDelete = ref(false);
    const locale = ref('fa');
    const categoryId = ref(null);

    const { isVisible } = useModal('editCat')

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

    const findLocaleTranslation = computed(() => {
      const foundTranslation = categoryRowModel.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;
    });

    watch(
        () => props.parents,
        (newVal) => {
          localParents.value = newVal
    },{ immediate: true,deep: true })

    watch(isVisible, (visible) => {
      if (visible) {
        console.log(props.categoryRow,'props.categoryRow')
        selectedPaernt.value = categoryRowModel.value?.parent?.id

        locale.value = categoryRowModel.value?.translation?.locale

        title.value = categoryRowModel.value?.translation?.title

        description.value = categoryRowModel.value?.translation?.description
      }
    });

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

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

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

      try {
        loading.value = true;

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

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

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

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

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

          categoryRowModel.value = updatedCategory;

          toast.success(data?.message)

          setTimeout(() => {
            emit("cat-updated");
          }, 500)
        }

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

    const handlerSubmitCategory = async () => {
      try {
        loadingStep.value = true;

        const { data: { success, data, message } } = await ApiServiece.put(
            `admin/categories/${categoryRowModel.value?.id}`, {
                parent_id: selectedPaernt.value
        }, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem("token")}`,
          },
        });

        if(success) {
          categoryId.value = data?.id

          emit("cat-updated")

          toast.success(message)
        }
      } catch (e) {
        toast.error(e?.response?.data?.message)
      } finally {
        loadingStep.value = false;
      }
    };

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

      if (findLocale) {
        title.value = findLocale?.title

        description.value = findLocale?.description
      } else {
        title.value = undefined

        description.value = undefined
      }
    }

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

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

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

          if (success) {
            const updatedCategory = props.categoryRow

            updatedCategory.translations = data?.translations

            categoryRowModel.value = updatedCategory

            title.value = ""

            description.value = ""

            toast.success(message)
          }
        } catch (e) {
          console.log(e)
        }finally {
          loadingDelete.value = false
        }
      }
    }

    return {
      errors,
      loading,
      clearError,
      editCat,
      image,
      title,
      description,
      localParents,
      selectedPaernt,
      locale,
      loadingStep,
      loadingDelete,
      handlerSubmitCategory,
      handlerChangeLocale,
      handlerRemoveTranslation,
      findLocaleTranslation
    };
  },
};
</script>

<style>
.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;
}
.icon-item {
  display: inline-block;
  width: 33%;
  padding: 5px;
  text-align: center;
}
.icon-container i {
  font-size: 2rem;
  margin-right: 10px;
}
.selected-icon-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
}

.selected-icon-container i {
  font-size: 2.5rem;
}

.icon-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 8px;
}

.steppy-item-title {
  white-space: nowrap;
}

.steppy-progress-bar {
  right: 0
}

.steppy-pane {
  text-align: right !important;
  box-shadow: none !important;
  padding: 0 !important;
}

.btn--default-2 {
  margin-right: auto;
  margin-left: unset !important;
}

.controls {
  display: none !important;
}

.wrapper-steppy {
  padding: 10px;
}
</style>
