<template>
  <div
    class="modal fade"
    id="editBlogCat"
    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">
          <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>
                  <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>

              <BCol lg="6">
                <div class="form-group">
                  <label class="form-label">عنوان دسته</label>
                  <input
                      v-model="titleCat"
                      @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>
            </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="closeAddBlogCat"
              >
                بستن
              </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 { iconData } from "@/views/live-preview/icon/data";
import {computed, ref, watch} from "vue";
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import ApiServiece from "@/services/ApiService";

export default {
  props: {
    icon: {
      type: String,
      Required: true,
    },
    title: {
      type: String,
      Required: true,
    },
    id: {
      type: String,
      Required: true,
    },
    catRow: {
      type: Object,
      Required: true,
    },
  },
  setup(props, { emit }) {
    const errors = ref({});
    const loading = ref(false);
    const loadingDelete = ref(false);
    const titleCat = ref(null);
    const locale = ref("fa");

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

    watch(
      () => props.catRow,
      (newVal) => {
        titleCat.value = newVal?.translation?.title

        locale.value = newVal?.translation?.locale
      }
    )

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

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

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

      try {
        loading.value = true;

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

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

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

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

          updatedCategory.translations = data?.data?.translations

          categoryRowModel.value = updatedCategory

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

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

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

    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;
    });

    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/blog-categories/${categoryRowModel.value?.id}/translations/${findLocale?.id}`
          )

          if (success) {
            const updatedCategory = props.catRow

            updatedCategory.translations = data?.translations

            categoryRowModel.value = updatedCategory

            titleCat.value = null

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

    return {
      errors,
      loading,
      clearError,
      editCat,
      iconData,
      titleCat,
      locale,
      handlerChangeLocale,
      findLocaleTranslation,
      handlerRemoveTranslation,
      loadingDelete,
    };
  },
};
</script>

<style scoped>
.modal-dialog {
  max-width: 50%;
}

.modal-content {
  padding: 1.5rem;
}

.modal-body {
  padding: 1rem 1.5rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.input-group {
  margin-top: 0.5rem;
}

.modal-header {
  border-bottom: 1px solid #dee2e6;
  padding-bottom: 1rem;
}

.Image-Preview {
  min-width: 100px;
  max-height: 100px;
  max-width: 100px;
  object-fit: cover;
  border-radius: 8px;
  border: 1px solid #ddd;
}

.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;
}

.icon-container i {
  font-size: 2rem;
  margin-right: 10px;
}

.icon-item {
  display: inline-block;
  width: 33%;
  padding: 5px;
  text-align: center;
}
</style>
