<template>
  <Layout>
    <BRow>
      <BCol sm="12">
        <BCard no-body>
          <BCardHeader>
            <h5>ایجاد محصول</h5>
          </BCardHeader>
          <BCardBody>
            <BRow class="g-3">
              <BCol md="6">
                <div class="form-group">
                  <label class="form-label">عنوان </label>
                  <input
                    type="text"
                    v-model="title"
                    class="form-control"
                    placeholder="عنوان محصول"
                    :class="{ 'is-invalid': errors.title }"
                    @input="clearError('title')"
                  />
                </div>
                <small v-if="errors.title" class="text-danger">
                  {{ errors.title }}
                </small>
              </BCol>

              <BCol md="6">
                <div class="form-group">
                  <label class="form-label">کلمه کلیدی</label>
                  <input
                    type="text"
                    v-model="slug"
                    class="form-control"
                    placeholder="کلمه کلیدی محصول"
                    :class="{ 'is-invalid': errors.slug }"
                    @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="summary"
                    class="form-control"
                    placeholder="خلاصه ای از محصول"
                    :class="{ 'is-invalid': errors.summary }"
                    @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="description"
                    class="form-control"
                    placeholder="توضیحات محصول"
                    :class="{ 'is-invalid': errors.description }"
                    @input="clearError('description')"
                  />
                </div>
                <small v-if="errors.description" class="text-danger">
                  {{ errors.description }}
                </small>
              </BCol>

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

                  <input
                    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>
                  <select
                    :class="{ 'is-invalid': errors.productType }"
                    v-model="productType"
                    class="form-control"
                    @change="clearError('productType')"
                  >
                    <option value="" disabled selected>
                      انتخاب حالت محصول
                    </option>
                    <option value="1">تک</option>
                    <option value="2">عمده</option>
                    <option value="3">هردو</option>
                  </select>
                </div>
                <small v-if="errors.productType" class="text-danger">
                  {{ errors.productType }}
                </small>
              </BCol>

              <BCol md="6" v-if="productType == 2 || productType == 3">
                <div class="form-group">
                  <label class="form-label">قیمت (عمده) </label>
                  <input
                    type="number"
                    v-model="wholesalePrice"
                    class="form-control"
                    placeholder="قیمت"
                    :class="{ 'is-invalid': errors.wholesalePrice }"
                    @input="clearError('wholesalePrice')"
                  />
                </div>
                <small v-if="errors.wholesalePrice" class="text-danger">
                  {{ errors.wholesalePrice }}
                </small>
              </BCol>

              <BCol md="6">
                <div class="form-group">
                  <label class="form-label">تعداد در کارتن</label>
                  <input
                    type="number"
                    v-model="countInCarton"
                    class="form-control"
                    placeholder="تعداد"
                    :class="{ 'is-invalid': errors.countInCarton }"
                    @input="clearError('countInCarton')"
                  />
                </div>
                <small v-if="errors.countInCarton" class="text-danger">
                  {{ errors.countInCarton }}
                </small>
              </BCol>

              <BCol v-if="productType == 1 || productType == 3" md="6">
                <div class="form-group">
                  <label class="form-label">قیمت (تک) </label>
                  <input
                    type="number"
                    v-model="retailePrice"
                    class="form-control"
                    placeholder="قیمت"
                    :class="{ 'is-invalid': errors.retailePrice }"
                    @input="clearError('retailePrice')"
                  />
                </div>
                <small v-if="errors.retailePrice" class="text-danger">
                  {{ errors.retailePrice }}
                </small>
              </BCol>

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

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

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

              <BCol v-if="spescial" md="6">
                <div class="form-group">
                  <label class="form-label"> تخفیف ویژه </label>
                  <input
                    type="number"
                    class="form-control"
                    placeholder="قیمت"
                    :class="{ 'is-invalid': errors.spescialPrice }"
                    @input="clearError('spescialPrice')"
                    v-model="spescialPrice"
                  />
                </div>
                <small v-if="errors.spescialPrice" class="text-danger">
                  {{ errors.spescialPrice }}
                </small>
              </BCol>

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

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

              <BCol md="6">
                <div class="form-group">
                  <label class="form-label">دسته</label>
                  <select
                    :class="{ 'is-invalid': errors.selectedCat }"
                    v-model="selectedCat"
                    class="form-control"
                    @change="clearError('selectedCat')"
                    placeholder="انتخاب دسته محصول"
                  >
                    <option v-for="cat in cats" :key="cat.id" :value="cat.id">
                      {{ cat.title }}
                    </option>
                  </select>
                </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>
                  <select
                    :class="{ 'is-invalid': errors.selectedBrand }"
                    v-model="selectedBrand"
                    class="form-control"
                    @change="clearError('selectedBrand')"
                    placeholder="انتخاب برند محصول"
                  >
                    <option
                      v-for="brand in brands"
                      :key="brand.id"
                      :value="brand.id"
                    >
                      {{ brand.title }}
                    </option>
                  </select>
                </div>
                <small v-if="errors.selectedBrand" class="text-danger">
                  {{ errors.selectedBrand }}
                </small>
              </BCol>

              <BCard>
                <div class="card-header">
                  <h5 class="mb-0">اضافه کردن ویژگی ها</h5>
                </div>
                <BRow class="g-3 mt-2">
                  <template v-if="attrebutes.length === 0">
                    <BCol>
                      <div class="alert alert-info text-center">
                        هیچ ویژگی وجود ندارد برای اضافه کردن ویژگی کلیک کنید
                        <BButton
                          variant="success"
                          size="lg"
                          class="mt-1 px-4 py-2 shadow-lg rounded-pill"
                          data-bs-toggle="modal"
                          data-bs-target="#addAttribute"
                        >
                          <i class="fas fa-plus me-2"></i> کلیک کنید
                        </BButton>
                      </div>
                    </BCol>
                  </template>
                  <BCol
                    v-for="attrebute in attrebutes"
                    :key="attrebute.id"
                    md="6"
                    lg="4"
                  >
                    <div class="card shadow-sm">
                      <div class="card-body">
                        <label
                          class="form-label d-flex align-items-center mb-3"
                        >
                          <BCol md="2" class="d-flex justify-content-center">
                            <BFormCheckbox
                              :id="'checkbox-id-' + attrebute.id"
                              class="mr-2 test"
                              v-model="attrebute.isChecked"
                            />
                          </BCol>

                          <BCol
                            md="5"
                            class="d-flex align-items-center"
                            :style="{ color: attrebute.code }"
                          >
                            {{ attrebute.title }}
                          </BCol>

                          <BCol md="5">
                            <input
                              type="number"
                              class="form-control"
                              placeholder="تعداد"
                              :disabled="!attrebute.isChecked"
                              v-model="attrebute.value"
                              @input="clearError(`inventory_${attrebute.id}`)"
                            />
                          </BCol>
                        </label>
                        <small
                          v-if="errors[`inventory_${attrebute.id}`]"
                          class="text-danger"
                        >
                          {{ errors[`inventory_${attrebute.id}`] }}
                        </small>
                      </div>
                    </div>
                  </BCol>

                  <small v-if="errors.selectedAttributes" class="text-danger">
                    {{ errors.selectedAttributes }}
                  </small>
                </BRow>
              </BCard>

              <BCard>
                <div class="card-header">
                  <h5 class="mb-0">اضافه کردن مشخصه ها</h5>
                </div>

                <BRow class="g-3 mt-2">
                  <template v-if="relatedAttrebutes.length === 0">
                    <BCol>
                      <div class="alert alert-info text-center">
                        دسته ای انتخاب نکرده اید یا دسته انتخابی شما مشخصه ای در
                        خود ندارد برای اضافه کردن مشخصه کلیک کنید
                        <BButton
                          variant="success"
                          size="lg"
                          class="mt-1 px-4 py-2 shadow-lg rounded-pill"
                          data-bs-toggle="modal"
                          data-bs-target="#addIdentity"
                        >
                          <i class="fas fa-plus me-2"></i> کلیک کنید
                        </BButton>
                      </div>
                    </BCol>
                  </template>

                  <template v-else>
                    <BCol
                      v-for="identity in relatedAttrebutes"
                      :key="identity.id"
                      md="6"
                      lg="4"
                    >
                      <div class="card shadow-sm">
                        <div class="card-body">
                          <label
                            class="form-label d-flex align-items-center mb-3"
                          >
                            <BCol md="2" class="d-flex justify-content-center">
                              <BFormCheckbox
                                :id="'checkbox-id-' + identity.id"
                                class="mr-2 test"
                                v-model="identity.isChecked"
                              />
                            </BCol>

                            <BCol md="5" class="d-flex align-items-center">
                              {{ identity.title }}
                            </BCol>

                            <BCol md="5">
                              <input
                                type="text"
                                class="form-control"
                                placeholder="مقدار"
                                :disabled="!identity.isChecked"
                                v-model="identity.value"
                                @input="clearError(`identity${identity.id}`)"
                              />
                            </BCol>
                          </label>
                          <small
                            v-if="errors[`identityVal_${identity.id}`]"
                            class="text-danger"
                          >
                            {{ errors[`identityVal_${identity.id}`] }}
                          </small>
                        </div>
                      </div>
                    </BCol>

                    <small v-if="errors.selectedIdentities" class="text-danger">
                      {{ errors.selectedIdentities }}
                    </small>
                  </template>
                </BRow>
              </BCard>

              <BCard>
                <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"
                        />
                      </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()"
                          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="text-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>
                </div>
              </BCard>
            </BRow>
          </BCardBody>
          <BCardFooter>
            <div class="d-flex justify-content-center">
              <div class="text-center">
                <button
                  type="submit"
                  class="btn btn-primary"
                  @click.prevent="submitForm"
                  :disabled="loading"
                >
                  <span v-if="loading">
                    <i class="fa fa-spinner fa-spin"></i> بارگذاری...
                  </span>
                  <span v-else>ایجاد</span>
                </button>
              </div>
            </div>
          </BCardFooter>
          <addIdentity :cats="cats" />
          <addAttribute
            :attributeValues="attributeValues"
            @attribute-updated="handleAttributeUpdated()"
          />
        </BCard>
      </BCol>
    </BRow>
  </Layout>
</template>

<script>
import addAttribute from "@/components/modals/attribute/addAttribute.vue";
import moment from "moment";
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import ApiServiece from "@/services/ApiService";
import { ref, onMounted, watch } from "vue";
import Layout from "@/layout/custom.vue";
import DatePicker from "vue3-persian-datetime-picker";
import addIdentity from "@/components/modals/identity/addIdentity.vue";
export default {
  name: "SAMPLE-PAGE",
  components: {
    Layout,
    DatePicker,
    addIdentity,
    addAttribute,
  },
  setup() {
    const attributeValues = ref();
    const relatedAttrebutes = ref([]);
    const countInCarton = ref();
    const selectedAttributes = ref();
    const selectedIdentities = ref();
    const expire = ref();
    const chosenPrice = ref();
    const spescialPrice = ref();
    const wholesalePrice = ref();
    const retailePrice = ref();
    const description = 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 isChosen = 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 cats = ref([]);
    const editorContent = ref("");

    const getCats = () => {
      ApiServiece.get(`admin/categories`)
        .then((resp) => {
          cats.value = resp.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    };

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

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

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

    const handleInput = () => {
      if (expire.value) {
        // Convert from Jalali to Georgian (Gregorian)
        expire.value = moment(expire.value, "jYYYY/jMM/jDD HH:mm:ss").format(
          "YYYY-MM-DD HH:mm:ss"
        );
      } else {
        expire.value = null;
        clearError("expire");
      }
    };

    const getBrands = () => {
      ApiServiece.get(`admin/brands`)
        .then((resp) => {
          brands.value = resp.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    };

    const getAttrebuteValues = () => {
      ApiServiece.get(`admin/attribute-values?attribute_id=1`)
        .then((resp) => {
          attrebutes.value = resp.data.data;
          console.log(attrebutes.value);
        })
        .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
        );
      }

      console.log(productAttributes.value);
    };

    const removeImage = (index) => {
      images.value.splice(index, 1);
    };

    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 (!title.value) errors.value.title = "وارد کردن عنوان محصول الزامی است";
      if (!slug.value)
        errors.value.slug = "وارد کردن کلمه کلیدی محصول ضروری می باشد";
      if (!summary.value)
        errors.value.summary = "وارد کردن خلاصه محصول ضروری می باشد";
      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 (!isChosen.value && spescial.value == 0)
        errors.value.isChosen = "انتخاب کنید محصول منتخب هست یا خیر";
      if (!spescial.value && isChosen.value == 0)
        errors.value.spescial = "انتخاب کنید محصول ویژه هست یا خیر";
      if (!retailePrice.value && productType.value == 1)
        errors.value.retailePrice = "قیمت محصول تک را وارد نمایید";
      if (!wholesalePrice.value && productType.value == 2)
        errors.value.wholesalePrice = "قیمت محصول عمده را وارد نمایید";
      if (!spescialPrice.value && spescial.value == 1 && isChosen.value == 0)
        errors.value.spescialPrice = "تخفیف محصول ویژه را وارد کنید";
      if (!chosenPrice.value && isChosen.value == 1 && spescial.value == 0)
        errors.value.chosenPrice = "تخفیف محصول منتخب را وارد کنید";
      if (!expire.value && spescial.value == 1 && isChosen.value == 0)
        errors.value.expire = "تاریخ انقضای محصول ویژه را انتخاب نمایید";
      if (!selectedBrand.value)
        errors.value.selectedBrand = "انتخاب برند برای محصول ضروری می باشد";

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

      if (images.value.length <= 0)
        errors.value.images = "انتخاب عکس برای محصول ضروری می باشد";

      const missingInventory = attrebutes.value.filter(
        (attribute) =>
          attribute.isChecked &&
          (attribute.value == null || attribute.value === "")
      );

      if (missingInventory.length > 0) {
        missingInventory.forEach((attribute) => {
          errors.value[
            `inventory_${attribute.id}`
          ] = `مقدار موجودی برای ویژگی الزامی است`;
        });
      }

      const missingIdentityVal = relatedAttrebutes.value.filter(
        (identity) =>
          identity.isChecked &&
          (identity.value == null || identity.value === "")
      );

      if (missingIdentityVal.length > 0) {
        missingIdentityVal.forEach((identity) => {
          errors.value[
            `identityVal_${identity.id}`
          ] = `وارد کردن مقدار مشخصه الزامی می باشد`;
        });
      }

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

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

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

      loading.value = true;

      const formData = new FormData();
      formData.append("title", title.value);
      formData.append("slug", slug.value);
      formData.append("summary", summary.value);
      formData.append("description", description.value);
      if (productType.value == 2) {
        formData.append("wholesale_price", wholesalePrice.value);
      }
      if (productType.value == 1) {
        formData.append("retail_price", retailePrice.value);
      }
      if (productType.value == 3) {
        formData.append("retail_price", retailePrice.value);
        formData.append("wholesale_price", wholesalePrice.value);
      }
      formData.append("type", productType.value);

      if (isChosen.value == 1 && spescial.value == 0) {
        formData.append("chosen_price", chosenPrice.value);
      }

      if (isChosen.value == 1 && spescial.value == 0) {
        formData.append("is_chosen", isChosen.value);
      }

      if (isChosen.value == 0 && spescial.value == 1) {
        formData.append("is_chosen", isChosen.value);
      }

      if (spescial.value == 1 && isChosen.value == 0) {
        formData.append("special_price", parseInt(spescialPrice.value, 10));
        formData.append("special_expires_at", expire.value);
      }

      if (spescial.value == 1 && isChosen.value == 0) {
        formData.append("is_special", spescial.value);
      }

      if (spescial.value == 0 && isChosen.value == 1) {
        formData.append("is_special", spescial.value);
      }

      formData.append("brand_id", selectedBrand.value);
      formData.append("category_id", selectedCat.value);
      formData.append("count_in_carton", countInCarton.value);
      formData.append("image", image.value);

      ApiServiece.post(`admin/products`, formData, {
        headers: {
          "content-type": "multipart",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      })
        .then((resp) => {
          id = resp.data.data.id;
          console.log(id);

          selectedAttributes.value = attrebutes.value
            .filter((attribute) => attribute.isChecked)
            .map((attribute) => ({
              attribute_value_id: attribute.id,
              inventory: attribute.value,
              type: productType.value,
            }));

          const finalPayload = {
            productAttributes: selectedAttributes.value,
          };

          const jsonString = JSON.stringify(finalPayload, null, 2);

          console.log(jsonString);
          ApiServiece.post(`admin/products/${id}/attributes`, jsonString)
            .then(() => {
              selectedIdentities.value = relatedAttrebutes.value
                .filter((identity) => identity.isChecked)
                .map((identity) => ({
                  attribute_id: identity.id,
                  attribute_value_title: identity.value,
                }));

              const finalPayload = {
                productSolidAttributes: selectedIdentities.value,
              };

              const jsonString = JSON.stringify(finalPayload, null, 2);
              ApiServiece.post(
                `admin/products/${id}/solid-attributes`,
                jsonString
              ).then((resp) => {
                console.log(resp);
              });
            })
            .then((resp) => {
              console.log(resp);
              images.value.map((image) => {
                console.log(image.file);
                const formData = new FormData();
                formData.append("image", image.file);
                ApiServiece.post(`admin/products/${id}/images`, formData, {
                  headers: {
                    "content-type": "multipart",
                    Authorization: `Bearer ${localStorage.getItem("token")}`,
                  },
                });
              });
            });
        })

        .then(() => {
          loading.value = false;
          toast.success("!محصول با موفقیت اضافه شد", {
            position: "top-right",
            autoClose: 1000,
          });
        })

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

    return {
      title,
      slug,
      summary,
      editor,
      cats,
      errors,
      image,
      imagePreview,
      handleImageChange,
      removeImage,
      submitForm,
      clearError,
      editorContent,
      author,
      blogCat,
      loading,
      productType,
      isChosen,
      spescial,
      date,
      selectedCat,
      brands,
      selectedBrand,
      attrebutes,
      images,
      addImage,
      handleImageUpload,
      selectedAttributes,
      description,
      onCheckboxChange,
      retailePrice,
      wholesalePrice,
      spescialPrice,
      chosenPrice,
      expire,
      handleInput,
      countInCarton,
      relatedAttrebutes,
      selectedIdentities,
      attributeValues,
      handleAttributeUpdated,
    };
  },
};
</script>

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