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

  const defaultFormState = {
    title: null,
    slug: null,
    summary: null,
    description: null,
    locale: 'fa'
  };

  const props = defineProps({
    productId: {
      type: Number,
      required: true,
    },
    product: {
      type: Object,
      required: true,
    },
  })

  const emit = defineEmits(["changeLng", "data", "update:productRow"]);

  const form = reactive({ ...defaultFormState });

  const errors = ref({})

  const loading = ref(false)

  const loadingDelete = ref(false)

  const productRowModel = computed({
    get: () => props.product,
    set: (newValue) => emit('update:productRow', newValue)
  });

  const findLocaleTranslation = computed(() => {
    const foundTranslation = props.product?.translations?.find(
        item => item?.locale === form.locale
    );
  
    if (foundTranslation) {
      switch (foundTranslation?.locale) {
        case "en":
          return "انگلیسی";
        case "fa":
          return "فارسی";
        case "ar":
          return "عربی";
        default:
          return null;
      }
    }

    return null;
  });

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

  const submitForm = async () => {
    try {
      loading.value = true

      const url = form?.id ? `admin/products/${props.productId}/translations/${form?.id}` : `admin/products/${props.productId}/translations`

      const { data: { success, message, data } } = await ApiService[form?.id ? 'put' : 'post'](url, form)

      if (success) {
        Object.assign(form, defaultFormState)

        emit('data', data)

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

  const handlerRemoveTranslation = async () => {
    const findLocale = props.product?.translations?.find(item => item?.locale === form.locale);

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

        const { data: { success, message, data } } = await ApiServiece.delete(
            `admin/products/${props.product?.id}/translations/${findLocale?.id}`
        )

        if (success) {
          const updatedCategory = props.product

          updatedCategory.translations = data?.translations

          productRowModel.value = updatedCategory

          Object.assign(form, defaultFormState)

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

  defineExpose({ form })
</script>

<template>
  <div class="p-2">
    <BButton
      :disabled="!findLocaleTranslation"
      :loading="loadingDelete"
      @click="handlerRemoveTranslation"
      class="btn btn-sm rounded btn-danger d-block mt-2"
      style="margin-right: auto"
  >
    حذف ترجمه {{ findLocaleTranslation }}
  </BButton>
    <BRow class="g-3">
      <BCol md="6">
        <div class="form-group">
          <label class="form-label">عنوان</label>
          <input
              v-model="form.title"
              :class="{ 'is-invalid': errors.title }"
              class="form-control"
              placeholder="عنوان محصول"
              type="text"
              @input="clearError('title')"
          />
        </div>
        <small v-if="errors.title" class="text-danger">
          {{ errors.title }}
        </small>
      </BCol>

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

      <BCol md="6">
        <div class="form-group">
          <label class="form-label">کلمه کلیدی</label>
          <input
              v-model="form.slug"
              :class="{ 'is-invalid': errors.slug }"
              class="form-control"
              placeholder="کلمه کلیدی محصول"
              type="text"
              @input="clearError('slug')"
          />
        </div>
        <small v-if="errors.slug" class="text-danger">
          {{ errors.slug }}
        </small>
      </BCol>

      <BCol md="6">
        <div class="form-group">
          <label class="form-label">خلاصه</label>
          <textarea
              v-model="form.summary"
              :class="{ 'is-invalid': errors.summary }"
              class="form-control"
              placeholder="خلاصه ای از محصول"
              @input="clearError('summary')"
          />
        </div>
        <small v-if="errors.summary" class="text-danger">
          {{ errors.summary }}
        </small>
      </BCol>

      <BCol md="6">
        <div class="form-group">
          <label class="form-label">توضیحات محصول</label>
          <textarea
              v-model="form.description"
              :class="{ 'is-invalid': errors.description }"
              class="form-control"
              placeholder="توضیحات محصول"
              @input="clearError('description')"
          />
        </div>
        <small v-if="errors.description" class="text-danger">
          {{ errors.description }}
        </small>
      </BCol>
    </BRow>

    <button
        type="submit"
        class="btn btn-primary mt-4"
        :disabled="loading"
        @click.prevent="submitForm"
    >
        <span v-if="loading">
          <i class="fa fa-spinner fa-spin"></i>
        </span>
      <span v-else>ذخیره محصول</span>
    </button>
  </div>
</template>

<style scoped>

</style>