<template>
  <Layout>
    <BRow>
      <BCol sm="12">
        <BCard no-body>
          <BCardHeader>
            <h5>ایجاد محصول</h5>
          </BCardHeader>
          <BCardBody>

              <Steppy
                  v-model:step="step"
                  :tabs="[
                    { title: 'ایجاد محصول', isValid: true },
                    { title: 'بارگذاری تصاویر', isValid: true },
                    { title: 'ویژگی ها' , isValid: true },
                    { title: 'مشخصات' , isValid: true },
                    { title: 'زبان ها' , isValid: true },
                  ]"
                  backText="قبلی"
                  nextText="بعدی"
                  doneText="ذخیره"
                  primaryColor1="#04A9F5"
                  circleSize="45"
                  :finalize="() => {}"
                  @update:step="handlerStep"
              >
                  <template #1>
                    <BRow class="g-3">
                      <BCol md="6">
                        <div class="form-group">
                          <label class="form-label">قیمت محصول(بر واحد دلار)</label>
                          <input
                              type="number"
                              v-model="price"
                              class="form-control"
                              placeholder="قیمت دلاری محصول را وارد کنید"
                              :class="{ 'is-invalid': errors.price }"
                              @input="clearError('price')"
                          />
                        </div>
                        <small v-if="errors.price" class="text-danger">
                          {{ errors.price }}
                        </small>
                      </BCol>

                      <BCol md="6">
                        <div class="form-group">
                          <label class="form-label">تصویر محصول</label>

                          <input
                              ref="productImageRef"
                              type="file"
                              accept="image/*"
                              @change="handleImageUpload"
                              class="form-control"
                              :class="{ 'is-invalid': errors.image }"
                          />

                          <div v-if="imagePreview" class="mt-2">
                            <img
                                :src="imagePreview"
                                alt="Image Preview"
                                class="img-fluid rounded shadow-sm Image-Preview"
                            />
                            <button
                                type="button"
                                @click="removeImage()"
                                class="delete-btn"
                            >
                              <i class="fa fa-trash f-16"></i>
                            </button>
                          </div>

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

                      <BCol md="6">
                        <div class="form-group">
                          <label class="form-label">وزن</label>
                          <input
                              type="number"
                              v-model="weight"
                              class="form-control"
                              placeholder="وزن"
                              :class="{ 'is-invalid': errors.weight }"
                              @input="clearError('weight')"
                          />
                        </div>
                        <small v-if="errors.weight" class="text-danger">
                          {{ errors.weight }}
                        </small>
                      </BCol>

                      <BCol md="6">
                        <div class="form-group">
                          <label class="form-label">نوع محصول</label>
                          <select
                              :class="{ 'is-invalid': errors.discount_type }"
                              v-model="discount_type"
                              class="form-control"
                              @change="clearError('discount_type')"
                          >
                            <option value="0">عادی</option>
                            <option value="1">ویژه</option>
                            <option value="2">منتخب</option>
                          </select>
                        </div>
                        <small v-if="errors.discount_type" class="text-danger">
                          {{ errors.discount_type }}
                        </small>
                      </BCol>

                      <BCol v-if="discount_type != 0" md="6">
                        <div class="form-group">
                          <label class="form-label">درصد تخفیف</label>
                          <input
                              type="number"
                              v-model="discount_percentage"
                              class="form-control"
                              placeholder="میزان تخفیف به درصد"
                              :class="{ 'is-invalid': errors.discount_percentage }"
                              @input="clearError('discount_percentage')"
                          />
                        </div>
                        <small v-if="errors.discount_percentage" class="text-danger">
                          {{ errors.discount_percentage }}
                        </small>
                      </BCol>

                      <BCol v-if="discount_type == 1" md="6">
                        <div class="form-group">
                          <label class="form-label">
                            تاریخ انقضای تخفیف محصول ویژه
                          </label>

                          <DatePicker
                              :format="'jYYYY/jMM/jDD HH:mm:ss'"
                              type="datetime"
                              v-model="discount_expires_at"
                          ></DatePicker>
                        </div>
                        <small v-if="errors.discount_expires_at" class="text-danger">
                          {{ errors.discount_expires_at }}
                        </small>
                      </BCol>

                      <BCol md="6">
                        <div class="form-group">
                          <label class="form-label">دسته</label>
                          <VueSelect
                              :isLoading="categorySelectorLoader"
                              v-model="selectedCat"
                              :options="formattedCategories"
                              placeholder="دسته ای را انتخاب کنید"
                              @search="handleSearch"
                          />
                        </div>
                        <small v-if="errors.selectedCat" class="text-danger">
                          {{ errors.selectedCat }}
                        </small>
                      </BCol>

                      <BCol md="6">
                        <div class="form-group">
                          <label class="form-label">برند</label>
                          <VueSelect
                              v-model="selectedBrand"
                              :isLoading="brandSelectorLoader"
                              :options="formattedBrands"
                              placeholder="برندی را انتخاب کنید"
                              @search="handleBrandSearch"
                          />
                        </div>
                        <small v-if="errors.selectedBrand" class="text-danger">
                          {{ errors.selectedBrand }}
                        </small>
                      </BCol>

                      <div class="d-flex justify-content-center mt-5">
                        <div class="text-center">
                          <button
                              type="submit"
                              class="btn btn-primary"
                              :disabled="loading"
                              @click.prevent="submitForm"
                          >
                            <span v-if="loading">
                              <i class="fa fa-spinner fa-spin"></i> بارگذاری...
                            </span>
                            <span v-else>ایجاد</span>
                          </button>
                        </div>
                      </div>
                    </BRow>
                  </template>

                  <template #2>
                    <div
                        class="card-header text-center p-4"
                        style="background-color: #f7f7f7"
                    >
                      <h5 class="mb-0 text-dark">اضافه کردن عکس ها</h5>
                    </div>

                    <BRow class="g-4 mt-3">
                      <BCol
                          v-for="(image, index) in images"
                          :key="index"
                          class="mb-4"
                          md="6"
                      >
                        <div class="form-group position-relative">
                          <label class="form-label mb-2 fw-bold text-secondary">تصویر محصول</label>

                          <div class="custom-file">
                            <input
                                type="file"
                                accept="image/*"
                                @change="(event) => handleImageChange(event, index)"
                                class="form-control-file rounded-3 shadow-sm"
                                style="border: 1px solid #ddd; padding: 15px"
                            />

                            <button
                                :disabled="image?.loading"
                                @click="submitImage(images[index], image)"
                                class="btn btn-primary rounded-pill me-4"
                            >
                              <span v-if="image?.loading">
                                <i class="fa fa-spinner fa-spin"></i> بارگذاری...
                              </span>
                              <span v-else>ثبت تصویر</span>
                            </button>
                          </div>

                          <div v-if="image.preview" class="mt-3 position-relative">
                            <img
                                :src="image.preview"
                                alt="Image Preview"
                                class="img-fluid rounded-3 shadow-lg border Image-Preview"
                            />

                            <button
                                type="button"
                                @click="removeImage(index)"
                                class="delete-btn"
                            >
                              <i class="fa fa-trash f-16"></i>
                            </button>
                          </div>
                        </div>
                      </BCol>
                      <small v-if="errors.images" class="text-danger">
                        {{ errors.images }}
                      </small>
                    </BRow>

                    <div class="d-flex justify-content-between align-items-center mt-4">
                      <button
                          @click="addImage"
                          class="btn btn-primary rounded-pill px-5 py-3"
                          style="
                            font-size: 16px;
                            box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
                          "
                      >
                        <i class="fa fa-plus-circle me-2"></i> افزودن عکس جدید
                      </button>

                      <button
                          @click="step++"
                          class="btn btn-primary rounded-pill px-5 py-3"
                      >
                        مرحله بعد
                      </button>
                    </div>
                  </template>

                  <template #3>
                    <AtrributesProduct
                        :product-id="productId"
                        :category-id="categoryId"
                        @next-step="step++"
                    />

                    <div class="d-flex justify-content-between mt-5">
                      <button class="btn btn-primary" @click="step--">مرحله قبلی</button>
                      <button class="btn btn-primary" @click="step++">مرحله بعد</button>
                    </div>
                  </template>

                  <template #4>
                    <SpecificationsProduct
                        :category-id="categoryId"
                        :product-id="productId"
                        @next-step="step++"
                        @prev-step="step--"
                    />

                    <div class="d-flex justify-content-between mt-5">
                      <button class="btn btn-primary" @click="step--">مرحله قبلی</button>
                      <button class="btn btn-primary" @click="step++">مرحله بعد</button>
                    </div>
                  </template>

                  <template #5>
                    <ProductInfo
                        :product-id="productId"
                        @previousStep="step--"
                    />

                    <button class="btn btn-primary mt-5" @click="step--">مرحله قبلی</button>
                  </template>
              </Steppy>
          </BCardBody>
          <addIdentity
              @identity-updated="handleIdentityUpdate"
              :categoryId="selectedCat"
          />
          <addAttribute
            :attributeValues="attributeValues"
            @attribute-updated="handleAttributeUpdated()"
          />
        </BCard>
      </BCol>
    </BRow>

  </Layout>
</template>

<script>
import VueSelect from "vue3-select-component";
import addAttribute from "@/components/modals/attribute/addAttribute.vue";
import moment from "jalali-moment";
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import ApiServiece from "@/services/ApiService";
import { ref, onMounted, watch, computed } from "vue";
import Layout from "@/layout/custom.vue";
import DatePicker from "vue3-persian-datetime-picker";
import addIdentity from "@/components/modals/identity/addIdentity.vue";
import { Modal } from "bootstrap"
import { Steppy } from 'vue3-steppy'
import AtrributesProduct from "@/components/AtrributesProduct.vue";
import SpecificationsProduct from "@/components/SpecificationsProduct.vue";
import ProductInfo from "@/components/ProductInfo.vue";

export default {
  name: "SAMPLE-PAGE",
  components: {
    ProductInfo,
    SpecificationsProduct,
    AtrributesProduct,
    Layout,
    DatePicker,
    addIdentity,
    addAttribute,
    VueSelect,
    Steppy,
  },
  setup() {
    const categorySelectorLoader = ref(false);
    const categories = ref([]);
    const brandSelectorLoader = ref(false);
    const attributeValues = ref();
    const relatedAttrebutes = ref([]);
    const weight = ref();
    const selectedAttributes = ref();
    const selectedIdentities = ref();
    const discount_expires_at = ref();
    const discount_percentage = ref();
    const spescialPrice = ref();
    const price = ref();
    const retailePrice = ref();

    const productAttributes = ref([]);
    const images = ref([{ file: null, preview: null }]);
    const brands = ref();
    const attrebutes = ref([]);
    const selectedBrand = ref();
    const selectedCat = ref();
    const date = ref();
    const spescial = ref("");
    const discount_type = ref("");
    const productType = ref();
    const loading = ref(false);
    const image = ref();
    const imagePreview = ref();
    const errors = ref({});
    const title = ref("");
    const slug = ref("");
    const summary = ref("");
    const blogCat = ref();
    const author = ref("");
    const editor = ref(null);
    const editorContent = ref("");
    const productId = ref(null);
    const loadingImage = ref(false);
    const imagesResponse = ref([]);
    const categoryId = ref(null);

    // ALIREZA
    const productImageRef = ref(null)
    const description = ref(null);
    const step = ref(1);


    const getAttributeValues = () => {
      ApiServiece.get(`admin/attributes`).then((resp) => {
        console.log(resp);
        attributeValues.value = resp.data.data;
      });
    };

    const handleAttributeUpdated = () => {
      getAttrebuteValues();
    };

    watch(selectedCat, (value) => {
      if (value){
        ApiServiece.get(`admin/attributes?category_id=${selectedCat.value}&with_global=1`)
            .then((resp) => {
              relatedAttrebutes.value = resp?.data?.data
            })
            .catch((err) => {
              console.log(err);
         });
      }
    });

    const handleIdentityUpdate = () => {
      ApiServiece.get(`admin/attributes?category_id=${selectedCat.value}&with_global=1`)
        .then((resp) => {
          relatedAttrebutes.value = resp.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    };

    const handleBrandSearch = async (searchTerm) => {
      if (searchTerm?.length < 3) return;
      brandSelectorLoader.value = true;
      try {
        const response = await ApiServiece.get(
          `admin/brands?title=${searchTerm ?? ''}`
        );
        brands.value = response.data.data;
        brandSelectorLoader.value = false;
      } catch (error) {
        brandSelectorLoader.value = false;
        brands.value = [];
      }
    };

    const formattedBrands = computed(() =>
      Array.isArray(brands.value)
        ? brands.value.map((brand) => ({
            value: brand.id,
            label: brand?.translation?.title,
          }))
        : []
    );

    const handleSearch = async (searchTerm) => {
      if (searchTerm?.length < 3) return;
      categorySelectorLoader.value = true;
      try {
        const response = await ApiServiece.get(
          `admin/categories?title=${searchTerm ?? ''}`
        );
        categories.value = response.data.data;
        categorySelectorLoader.value = false;
      } catch (error) {
        categorySelectorLoader.value = false;
        categories.value = [];
      }
    };

    const formattedCategories = computed(() =>
      Array.isArray(categories.value)
        ? categories.value.map((category) => ({
            value: category.id,
            label: category?.translation?.title,
          }))
        : []
    );

    const getAttrebuteValues = () => {
      ApiServiece.get(`admin/attribute-values?attribute_id=1`)
        .then((resp) => {
          attrebutes.value = resp.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    };

    const onCheckboxChange = (attrebute) => {
      if (attrebute.isChecked) {
        productAttributes.value.push({
          attribute_value_id: attrebute.id,
          type: 1,
          inventory: attrebute.value || 0,
        });
      } else {
        productAttributes.value = productAttributes.value.filter(
          (item) => item.attribute_value_id !== attrebute.id
        );
      }
    };

    const removeImage = async (index) => {
      if (!imagesResponse.value[index]) {
        images.value.splice(index, 1);
      } else {
        try {

          const { data } = await ApiServiece.post(`admin/products/${productId.value}/images`,{
            _method: 'DELETE',
            fileName: imagesResponse.value[index]
          })

          if (data.success){
            images.value.splice(index, 1);

            imagesResponse.value.splice(index, 1)

            toast.success(data?.message);
          }
        } catch (e) {
          toast.error(e.response.data.message)
        }
      }
    }

    const addImage = () => {
      images.value.push({ file: null, preview: null });
    };

    const handleImageChange = (event, index) => {
      const file = event.target.files[0];
      if (file) {
        if (!images.value[index]) {
          images.value[index] = {};
        }
        images.value[index].file = file;
        images.value[index].preview = URL.createObjectURL(file);
      }
    };

    const handleImageUpload = (event) => {
      const file = event.target.files[0];

      if (file) {
        errors.value.image = null;

        image.value = file;

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

    const validateForm = () => {
      errors.value = {};

      if (!weight.value)
        errors.value.weight = "وارد کردن وزن محصول ضروری می باشد";
      if (!selectedCat.value)
        errors.value.selectedCat = "انتخاب دسته برای محصول ضروری می باشد";

      if (!image.value)
        errors.value.image = "وارد کردن عکس محصول ضروری می باشد";
      // if (!description.value)
      //   errors.value.description = "وارد کردن توضیحات محصول ضروری می باشد";
      // if (!productType.value)
      //   errors.value.productType = "انتخاب حالت محصول ضروری می باشد";

      if (!discount_type.value)
        errors.value.discount_type = "انتخاب کنید محصول منتخب هست یا خیر";
      if (!price.value)
        errors.value.price = "قیمت محصول را وارد نمایید";
      if (!discount_expires_at.value && discount_type.value == 1)
        errors.value.discount_expires_at = "تاریخ انقضای محصول ویژه را انتخاب نمایید";
      if (!selectedBrand.value)
        errors.value.selectedBrand = "انتخاب برند برای محصول ضروری می باشد";

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

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

    const handleAddIdentityClick = () => {
      if (!selectedCat.value) {
        toast.error("لطفا ابتدا یک دسته‌بندی انتخاب کنید", {
          position: "top-right",
          autoClose: 3000
        });
        return;
      }

      const modal = new Modal(document.getElementById('addIdentity'));

      modal?.show();
    };

    const handlerStep = (s) => {
      console.log(s)
      //step.value = 1
    }

    onMounted(() => {
      // const quill = new Quill(editor.value, {
      //   theme: "snow",
      //   modules: {
      //     toolbar: [
      //       [{ header: "1" }, { header: "2" }, { font: [] }],
      //       [{ list: "ordered" }, { list: "bullet" }],
      //       [{ align: [] }],
      //       ["bold", "italic", "underline"],
      //       ["link", "image"],
      //       [{ script: "sub" }, { script: "super" }],
      //       [{ direction: "rtl" }],
      //     ],
      //   },
      // });
      //
      // quill.root.setAttribute("dir", "rtl");
      // quill.format("direction", "rtl");
      //
      // nextTick(() => {
      //   const rtlButton = quill.container.querySelector(
      //     ".ql-direction[data-value='rtl']"
      //   );
      //   if (rtlButton) {
      //     rtlButton.click();
      //   }
      // });
      //
      // quill.on("text-change", () => {
      //   editorContent.value = quill.root.innerHTML;
      // });
      //getAttrebuteValues();
      getAttributeValues();
      handleBrandSearch();
    });

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

      loading.value = true;

      const formData = new FormData();

      if (discount_type.value != 0){
        formData.append("discount_type", discount_type.value);

        formData.append("discount_percentage", discount_percentage.value);
      }

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

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

      if (discount_type.value == 1) {
        const georgianDate = moment(
          discount_expires_at.value,
          "jYYYY/jMM/jDD HH:mm:ss"
        ).format("YYYY/MM/DD HH:mm:ss");

        formData.append("discount_expires_at", georgianDate);
      }

      formData.append("brand_id", selectedBrand.value);

      formData.append("category_id", selectedCat.value);

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

      ApiServiece.post(`admin/products`, formData, {
        headers: {
          "content-type": "multipart/form-data",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      })
        .then((resp) => {
          step.value++

          productId.value = resp?.data?.data?.id;

          categoryId.value = resp?.data?.data?.category_id;

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

    const submitImage = async (file, image) => {
      if (!file?.file) {
        toast.error('لطفا یک تصویر بارگذاری کنید.')

        return
      }

      try {
        image.loading = true;

        const formData = new FormData();

        formData.append("image", file?.file);

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

        if (success) {
          toast.success(message)

          imagesResponse.value = data?.images
        }
      } catch (e) {
        toast.error(e.response?.data?.message)
      } finally {
        image.loading = false;
      }
    }

    onMounted(() => {
      handleSearch()
    })

    return {
      title,
      slug,
      summary,
      editor,
      errors,
      image,
      imagePreview,
      handleImageChange,
      removeImage,
      submitForm,
      clearError,
      editorContent,
      author,
      blogCat,
      loading,
      productType,
      discount_type,
      spescial,
      date,
      selectedCat,
      brands,
      selectedBrand,
      attrebutes,
      images,
      step,
      addImage,
      handleImageUpload,
      selectedAttributes,
      onCheckboxChange,
      retailePrice,
      price,
      spescialPrice,
      discount_percentage,
      discount_expires_at,
      weight,
      relatedAttrebutes,
      selectedIdentities,
      attributeValues,
      handleAttributeUpdated,
      handleIdentityUpdate,
      handleBrandSearch,
      brandSelectorLoader,
      formattedBrands,
      handleSearch,
      formattedCategories,
      categorySelectorLoader,
      productImageRef,
      description,
      handleAddIdentityClick,
      handlerStep,
      submitImage,
      loadingImage,
      imagesResponse,
      productId,
      categoryId
    };
  },
};
</script>

<style>
:root {
  --vue-simple-stepper-primary-color: #04A9F5;
  --vue-simple-stepper-primary-color-contrast: white;
}

.ql-editor {
  direction: rtl;
  text-align: right;
}

.ql-editor::before {
  content: attr(placeholder);
  direction: rtl !important;
  text-align: right;
}
.Image-Preview {
  min-width: 200px;
  max-height: 200px;
  min-height: 200px;
  max-width: 200px;
  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;
  margin-right: 200px;
}

.delete-btn:hover {
  background-color: #c0392b;
  transform: scale(1.05);
}

.delete-btn:active {
  background-color: #a93226;
}

.delete-btn:focus {
  outline: none;
}
</style>
