<template>
  <div
    class="modal fade"
    id="editBrand"
    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-4">
                <label class="form-label">تصویر برند</label>

                <input
                    type="file"
                    @input="clearError('localImage')"
                    accept="image/*"
                    @change="handleImageChange"
                    class="form-control"
                    :class="{ 'is-invalid': errors.localImage }"
                />

                <div v-if="imagePreview" class="mt-2">
                  <img
                      :src="imagePreview"
                      alt="Image Preview"
                      class="img-fluid rounded shadow-sm Image-Preview"
                  />
                </div>

                <small v-if="errors.localImage" class="text-danger">
                  {{ errors.localImage }}
                </small>
              </div>

              <div
                  class="d-flex justify-content-end gap-2"
                  style="margin-top: 20px"
              >
                <button :disabled="loadingImage" @click="editImageBrand" class="btn btn-primary">
                  <span
                      v-if="loadingImage"
                      class="spinner-border spinner-border-sm"
                      role="status"
                      aria-hidden="true"
                  />
                  ذخیره
                </button>
              </div>
            </BTab>
            <BTab title="ترجمه ها">
              <form @submit.prevent="editBrand" 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('localTitle')"
                          type="text"
                          class="form-control"
                          placeholder="عنوان برند"
                          :class="{ 'is-invalid': errors.localTitle }"
                      />
                      <small v-if="errors.localTitle" class="text-danger">
                        {{ errors.localTitle }}
                      </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">
                  <!-- Brand Description -->
                  <BCol lg="12">
                    <div class="form-group">
                      <label class="form-label">توضیحات برند</label>
                      <textarea
                          v-model="localDesc"
                          @input="clearError('localDesc')"
                          type="text"
                          class="form-control"
                          placeholder="توضیحات برند"
                          :class="{ 'is-invalid': errors.localDesc }"
                      ></textarea>
                      <small v-if="errors.localDesc" class="text-danger">
                        {{ errors.localDesc }}
                      </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="closeEdit"
                  >
                    بستن
                  </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>
            </BTab>
          </BTabs>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {computed, ref, toRef, watch} from "vue";
import ApiServiece from "@/services/ApiService";

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

export default {
  components: {BTabs},
  props: {
    id: {
      type: String,
      required: true,
    },
    title: {
      type: String,
      required: true,
    },
    description: {
      type: String,
      required: true,
    },
    image: {
      type: String,
      required: true,
    },
    brandRow: {
      type: Object,
      required: true,
    },
  },

  setup(props, { emit }) {
    const imagePreview = ref(null);
    const localTitle = toRef(props.title);
    const localDesc = toRef(props.description);
    const localImage = toRef(props.image);
    const image = ref(null);
    const errors = ref({});
    const loading = ref(false);
    const loadingImage = ref(false);
    const locale = ref('fa');
    const loadingDelete = ref(false);

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

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

          localDesc.value = newVal?.translation?.description

          locale.value = newVal?.translation?.locale

          imagePreview.value = newVal?.image
        }
    )

    const findLocaleTranslation = computed(() => {
      const foundTranslation = brandRowModel.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 handleImageChange = (event) => {
      const file = event.target.files[0];

      if (file) {
        if (!file.type.startsWith("image/")) {
          errors.value.image = "لطفا یک فایل تصویری انتخاب کنید";
          imagePreview.value = null;
          return;
        }

        errors.value.localImage = null;

        image.value = file;

        const reader = new FileReader();
        reader.onload = () => {
          imagePreview.value = reader.result;
        };
        reader.readAsDataURL(file);
      }
    };

    const validateForm = () => {
      errors.value = {};
      if (!localTitle.value)
        errors.value.localTitle = "وارد کردن عنوان برند ضروری می باشد";
      if (!localDesc.value)
        errors.value.localDesc = "وارد کردن توضیحات برند ضروری می باشد";
      if (!localImage.value && !imagePreview.value) {
        errors.value.localImage = "یک عکس انتخاب نمایید";
      }
      return Object.keys(errors.value).length === 0;
    };

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

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

      try {
        loading.value = true;

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

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

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

        if (data?.success) {
          const updatedCategory = brandRowModel.value;

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

          brandRowModel.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 editImageBrand = async () => {
      try {
        loadingImage.value = true;

        const formData = new FormData();

        formData.append("image", image.value);

        formData.append("_method", 'put');

        const { data: { message, success } } = await ApiServiece.post(
            `admin/brands/${brandRowModel.value?.id}`,
            formData,
            {
              headers: {
                "content-type": "multipart",
                Authorization: `Bearer ${localStorage.getItem("token")}`,
              },
            })

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

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

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

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

          if (success) {
            const updatedBrand = brandRowModel.value;

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

            brandRowModel.value = updatedBrand;

            localTitle.value = null

            localDesc.value = null

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

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

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

        localDesc.value = findLocale?.description
      } else {
        localTitle.value = undefined

        localDesc.value = undefined
      }
    }

    return {
      errors,
      loading,
      clearError,
      editBrand,
      localTitle,
      localDesc,
      localImage,
      handleImageChange,
      imagePreview,
      locale,
      loadingImage,
      editImageBrand,
      findLocaleTranslation,
      handlerRemoveTranslation,
      loadingDelete,
      handlerChangeLocale
    };
  },
};
</script>

<style scoped>
.profile-upload-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.profile-upload-icon {
  font-size: 64px;
  color: #6c757d;
  border: 2px dashed #6c757d;
  border-radius: 50%;
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}
.modal-dialog {
  max-width: 50%;
}

.modal-content {
  padding: 20px;
}

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

.modal-body {
  padding: 20px;
}

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

.input-group {
  margin-top: 0.5rem;
}
.profile-upload-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.profile-upload-btn {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border: 2px solid #007bff;
  background-color: #ffffff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.profile-upload-btn i {
  font-size: 20px;
  color: #007bff;
}

.profile-image-preview {
  display: flex;
  justify-content: center;
  align-items: center;
}

.profile-placeholder {
  border: 2px dashed #007bff;
}

.d-none {
  display: none;
}
.profile-upload-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.profile-upload-btn {
  width: 30px;
  height: 30px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #ccc;
  background-color: #fff;
  cursor: pointer;
}

.profile-upload-btn i {
  font-size: 16px;
  color: #007bff;
}

.profile-image-preview img,
.profile-placeholder {
  width: 80px;
  height: 80px;
}

.profile-placeholder i {
  font-size: 40px;
}
.modal-dialog {
  max-width: 50%;
}

.modal-content {
  padding: 1.5rem; /* Increased padding for better spacing */
}

.modal-header {
  border-bottom: 1px solid #dee2e6;
  padding-bottom: 1rem; /* Added padding-bottom to separate the header from the content */
}

.modal-body {
  padding: 1rem 1.5rem; /* Adjusted padding for a more balanced layout */
}

.form-group {
  margin-bottom: 1.5rem; /* Increased margin between form groups */
}

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

.profile-image-preview:hover .overlay {
  opacity: 1;
}

.profile-image-preview:hover img,
.profile-image-preview:hover .profile-placeholder {
  opacity: 0.7;
}
.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;
}
</style>
