<script setup>
import { computed, ref, watch, defineProps, defineEmits } from "vue"
import { BRow } from "bootstrap-vue-next";
import {toast} from "vue3-toastify";
import ApiServiece from "@/services/ApiService";

const colorCode = ref(null)
const errors = ref({})
const loading = ref(false)
const attrName = ref(null)
const locale = ref('fa')
const loadingDelete = ref(false)

const props = defineProps({
  attrRow: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['update:categoryRow'])

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

watch(
    () => props.attrRow,
    (newVal) => {
      colorCode.value = newVal?.code

      attrName.value = newVal?.translation?.title

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

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 handlerChangeLocale = (e) => {
  const findLocale = attrRowModel.value?.translations?.find(item => item?.locale === e.target.value);

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

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

  try {
    loading.value = true;

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

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

    const { data } = existingTranslation
        ? await ApiServiece.put(
            `admin/attribute-values/${attrRowModel.value?.id}/translations/${existingTranslation?.id}`,
            params,
            {
              headers: {
                Authorization: `Bearer ${localStorage.getItem("token")}`,
              },
            }
        )
        : await ApiServiece.post(
            `admin/attribute-values/${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("cat-updated");
    }

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

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

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

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/attribute-values/${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;

        attrName.value = null

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

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

<template>
  <div
      class="modal fade"
      id="editAttributeValue"
      tabindex="-1"
      role="dialog"
      aria-labelledby="exampleModalLabel"
      aria-hidden="true"
  >
    <div class="modal-dialog">
      <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="editAttribute" class="mt-5">

            <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="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="انتخاب کنید"
                      @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>
<!--          <BTabs>-->
<!--            <BTab title="انتخاب رنگ">-->
<!--              <BRow>-->
<!--                <BCol class="mt-5">-->
<!--                  <div class="form-group">-->
<!--                    <label class="form-label">انتخاب رنگ</label>-->
<!--                    <div class="color-picker-wrapper">-->
<!--                      <input-->
<!--                          v-model="colorCode"-->
<!--                          @input="clearError('colorCode')"-->
<!--                          type="color"-->
<!--                          class="form-control color-picker"-->
<!--                          :class="{ 'is-invalid': errors.colorCode }"-->
<!--                      />-->
<!--                      <span-->
<!--                          v-if="colorCode"-->
<!--                          class="color-display"-->
<!--                          :style="{ backgroundColor: colorCode }"-->
<!--                      ></span>-->
<!--                    </div>-->
<!--                    <span>{{ colorCode }}</span>-->

<!--                    <small v-if="errors.colorCode" class="text-danger">-->
<!--                      {{ errors.colorCode }}-->
<!--                    </small>-->
<!--                  </div>-->
<!--                </BCol>-->
<!--              </BRow>-->

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

<!--                <button class="btn btn-primary" :disabled="loading" @click="handlerSubmitColor">-->
<!--                  <span-->
<!--                      v-if="loading"-->
<!--                      class="spinner-border spinner-border-sm"-->
<!--                      role="status"-->
<!--                      aria-hidden="true"-->
<!--                  />-->
<!--                  ذخیره-->
<!--                </button>-->
<!--              </div>-->
<!--            </BTab>-->
<!--            <BTab title="ترجمه ها">-->
<!--             -->
<!--            </BTab>-->
<!--          </BTabs>-->
        </div>
      </div>
    </div>
  </div>
</template>

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

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