<template>
  <Layout>
    <BRow>
      <BCol sm="12">
        <BCard no-body>
          <BCardHeader>
            <h5>ویرایش محصول</h5>
          </BCardHeader>
          <BCardBody>
            <BRow class="g-3">
              <!-- First Input Field -->
              <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>

              <!-- Second Input Field (Slug) -->
              <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>

              <!-- Summary Textarea -->
              <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"
                    />
                  </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"
                    @select="clearError('productType')"
                    placeholder="انتخاب حالت محصول"
                  >
                    <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" v-if="productType != 1">
                <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"
                    @select="clearError('isChosen')"
                    placeholder="انتخاب حالت منتخب"
                  >
                    <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.slug" class="text-danger">
                  {{ errors.slug }}
                </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"
                    @select="clearError('spescial')"
                    placeholder="انتخاب حالت ویژه"
                  >
                    <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 == 1" 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 == 1" md="6">
                <div class="form-group">
                  <label class="form-label">
                    تاریخ انقضای تخفیف محصول ویژه
                  </label>

                  <DatePicker
                    :format="'jYYYY/jMM/jDD HH:mm:ss'"
                    type="datetime"
                    v-model="expire"
                  ></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.blogCat }"
                    v-model="selectedCat"
                    class="form-control"
                    @input="clearError('selectedCat')"
                    placeholder="انتخاب دسته محصول"
                  >
                    <option v-for="cat in cats" :key="cat.id" :value="cat.id">
                      {{ cat.title }}
                    </option>
                  </select>
                </div>
                <small v-if="errors.blogCat" class="text-danger">
                  {{ errors.blogCat }}
                </small>
              </BCol> -->

              <BCol md="6">
                <div class="form-group">
                  <label class="form-label">دسته</label>
                  <VueSelect
                    :isLoading="categorySelectorLoader"
                    v-model="selectedCat"
                    :reduce="(option) => option.value"
                    :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"
                    :reduce="(option) => option.value"
                    placeholder="برندی را انتخاب کنید"
                    @search="handleBrandSearch"
                  />
                </div>
                <small v-if="errors.selectedBrand" class="text-danger">
                  {{ errors.selectedBrand }}
                </small>
              </BCol>

              <BCard v-if="locals.length !== 0">
                <BRow class="g-3 mt-2">
                  <div class="card-header">
                    <h5 class="mb-0">ویرایش ویژگی ها</h5>
                  </div>
                  <BCol
                    v-for="attrebute in locals"
                    :key="attrebute.id"
                    md="6"
                    lg="4"
                  >
                    <div class="card shadow-sm">
                      <div class="card-body">
                        <!-- Card Header with Delete Icon -->
                        <div
                          class="d-flex justify-content-between align-items-center"
                        >
                          <!-- Optional Title or Heading for the card -->
                          <div class="card-title"></div>

                          <!-- Delete Icon -->
                          <button
                            class="btn btn-link text-danger p-0"
                            @click="deleteAttribute(attrebute.id)"
                            title="حذف"
                          >
                            <i class="fas fa-trash-alt"></i>
                          </button>
                        </div>

                        <!-- Checkbox Column -->
                        <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>

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

                          <!-- Number Input Column -->
                          <BCol md="5">
                            <input
                              type="number"
                              class="form-control"
                              placeholder="تعداد"
                              :disabled="!attrebute.isChecked"
                              v-model="attrebute.value"
                              @input="clearError(`inventory_${attrebute.id}`)"
                            />
                          </BCol>
                        </label>

                        <!-- Error Message -->
                        <small
                          v-if="errors[`inventory_${attrebute.id}`]"
                          class="text-danger"
                        >
                          {{ errors[`inventory_${attrebute.id}`] }}
                        </small>

                        <!-- Edit Button -->
                        <div class="mt-3 text-center">
                          <button
                            class="btn btn-primary"
                            @click="
                              editAttribute(
                                attrebute.id,
                                attrebute.value,
                                attrebute.attribute_value_id
                              )
                            "
                          >
                            ویرایش
                          </button>
                        </div>
                      </div>
                    </div>
                  </BCol>

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

              <BCard v-if="localIdentities.length !== 0">
                <div class="card-header">
                  <h5 class="mb-0">ویرایش مشخصه ها</h5>
                </div>

                <BRow class="g-3 mt-2">
                  <!-- Loop through attributes -->
                  <BCol
                    v-for="identity in localIdentities"
                    :key="identity.id"
                    md="6"
                    lg="4"
                  >
                    <div class="card shadow-sm">
                      <div class="card-body">
                        <!-- Card Header with Delete Icon -->
                        <div
                          class="d-flex justify-content-between align-items-center"
                        >
                          <!-- Optional Title or Heading for the card -->
                          <div class="card-title">
                            <!-- You can add a title or leave it empty if you don't need one -->
                          </div>

                          <!-- Delete Icon -->
                          <button
                            class="btn btn-link text-danger p-0"
                            @click="deleteIdentity(identity.id)"
                            title="حذف"
                          >
                            <i class="fas fa-trash-alt"></i>
                          </button>
                        </div>

                        <!-- Checkbox Column -->
                        <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>

                          <!-- Title Column with Dynamic Color -->
                          <BCol md="5" class="d-flex align-items-center">
                            {{ identity.title }}
                          </BCol>

                          <!-- Number Input Column -->
                          <BCol md="5">
                            <input
                              type="text"
                              class="form-control"
                              placeholder="تعداد"
                              :disabled="!identity.isChecked"
                              v-model="identity.value"
                            />
                          </BCol>
                        </label>

                        <!-- Error Message -->

                        <!-- Edit Button -->
                        <div class="mt-3 text-center">
                          <button
                            class="btn btn-primary"
                            @click="
                              editIdentity(
                                identity.id,
                                identity.value,
                                identity.attribute_value_id
                              )
                            "
                          >
                            ویرایش
                          </button>
                        </div>
                      </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="attrebutes.length === 0 && !repeatedIdentity">
                    <BCol>
                      <div class="alert alert-info text-center">
                        برای شما ویژگی ثبت نشده است. برای ساختن یک ویژگی
                        <BButton
                          variant="success"
                          size="lg"
                          class="mt-2 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-if="attrebutes.length === 0 && repeatedAttrebute">
                    <BCol>
                      <div
                        class="alert alert-info text-center p-4 shadow-lg rounded-lg"
                      >
                        <h5 class="mb-3">
                          هیچ ویژگی جدیدی برای شما ثبت نشده است
                        </h5>
                        <p class="mb-3">
                          شما می‌توانید ویژگی های قبلی را ویرایش کنید.
                          <br />
                          برای اضافه کردن ویژگی جدید ، لطفاً دکمه زیر را کلیک
                          کنید .
                        </p>
                        <BButton
                          variant="success"
                          size="lg"
                          class="mt-3 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>

                  <!-- Loop through attributes -->
                  <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"
                        >
                          <!-- Checkbox Column -->
                          <BCol md="2" class="d-flex justify-content-center">
                            <BFormCheckbox
                              :id="'checkbox-id-' + attrebute.id"
                              class="mr-2 test"
                              v-model="attrebute.isChecked"
                            />
                          </BCol>

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

                          <!-- Number Input Column -->
                          <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>
                <template v-if="identities.length === 0 && !repeatedIdentity">
                  <BCol>
                    <div class="alert alert-info text-center">
                      برای شما مشخصه‌ای ثبت نشده است. برای ساختن یک مشخصه
                      <BButton
                        variant="success"
                        size="lg"
                        class="mt-2 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-if="identities.length === 0 && repeatedIdentity">
                  <BCol>
                    <div
                      class="alert alert-info text-center p-4 shadow-lg rounded-lg"
                    >
                      <h5 class="mb-3">
                        هیچ مشخصه جدیدی برای این دسته‌بندی ثبت نشده است
                      </h5>
                      <p class="mb-3">
                        شما می‌توانید مشخصه‌های قبلی را ویرایش کنید.
                        <br />
                        برای اضافه کردن مشخصه جدید به این دسته، لطفاً دکمه زیر
                        را کلیک کنید .
                      </p>
                      <BButton
                        variant="success"
                        size="lg"
                        class="mt-3 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>
                <BRow class="g-3 mt-2">
                  <!-- Loop through attributes -->
                  <BCol
                    v-for="identity in identities"
                    :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"
                        >
                          <!-- Checkbox Column -->
                          <BCol md="2" class="d-flex justify-content-center">
                            <BFormCheckbox
                              :id="'checkbox-id-' + identity.id"
                              class="mr-2 test"
                              v-model="identity.isChecked"
                            />
                          </BCol>

                          <!-- Title Column with Dynamic Color -->
                          <BCol md="5" class="d-flex align-items-center">
                            {{ identity.title }}
                          </BCol>

                          <!-- Number Input Column -->

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

              <BCard>
                <!-- Card Header -->
                <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 -->
                      <label class="form-label mb-2 fw-bold text-secondary"
                        >تصویر محصول</label
                      >

                      <!-- File Input -->
                      <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>

                      <!-- Image Preview Section -->
                      <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"
                        />

                        <!-- Delete Button -->
                        <button
                          type="button"
                          @click="removeImage(index, image.preview)"
                          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>

                <!-- Add New Image Upload Section -->
                <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>
            <addIdentity
              :cats="categories"
              @attribute-updated="handleAttributeUpdated()"
            />
            <addAttribute @attribute-updated="handleAttributeUpdated()" />
          </BCardFooter>
        </BCard>
      </BCol>
    </BRow>
  </Layout>
</template>

<script>
import VueSelect from "vue3-select-component";
import "quill/dist/quill.snow.css";
import Swal from "sweetalert2";
import { useRoute } from "vue-router";
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import moment from "jalali-moment";
import ApiServiece from "@/services/ApiService";
import { ref, onMounted, watch, computed } from "vue";
import Layout from "@/layout/custom.vue";
import addIdentity from "@/components/modals/identity/addIdentity.vue";
import addAttribute from "@/components/modals/attribute/addAttribute.vue";
import DatePicker from "vue3-persian-datetime-picker";

export default {
  name: "SAMPLE-PAGE",
  components: {
    Layout,
    DatePicker,
    addIdentity,
    addAttribute,
    VueSelect,
  },
  setup() {
    const locals = ref([
      {
        id: null,
        title: null,
        code: null,
        inventory: null,
        isChecked: null,
        attribute_value_id: null,
      },
    ]);

    const localIdentities = ref([]);
    const countInCarton = ref();
    const files = ref([]);
    const productValueId = ref();
    const localsIds = ref();
    const identities = ref([]);
    const localIdentitiesIds = ref([]);
    const selectedAttributes = ref();
    const selectedidentities = ref([]);
    const product = ref();
    const route = useRoute();
    const imagesTosend = ref();
    const expire = ref();
    const chosenPrice = ref();
    const spescialPrice = ref();
    const wholesalePrice = ref();
    const retailePrice = ref();
    const productAttributes = ref([]);
    const images = ref([{ file: null, preview: null }]);
    const localImages = ref([{ preview: null }]);

    const attrebutes = ref([]);
    const selectedBrand = ref();
    const selectedCat = ref();
    const date = ref();
    const spescial = ref(0);
    const isChosen = ref(0);
    const productType = ref();
    const loading = ref(false);
    const image = ref();
    const imagePreview = ref();
    const repeatedIdentity = ref(false);
    const repeatedAttrebute = ref(false);
    const errors = ref({});
    const title = ref("");
    const slug = ref("");
    const summary = ref("");
    const blogCat = ref();
    const author = ref("");
    const editor = ref(null);
    const categories = ref([{ id: null, title: "" }]);
    const brands = ref([{ id: null, title: "" }]);
    const editorContent = ref("");
    const categorySelectorLoader = ref(false);
    const brandSelectorLoader = ref(false);
    // ALIREZA
    const productImageRef = ref(null)
    const description = ref(null)



    const formattedCategories = computed(() =>
      Array.isArray(categories.value)
        ? categories.value.map((category) => ({
            value: category.id,
            label: category.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 formattedBrands = computed(() =>
      Array.isArray(brands.value)
        ? brands.value.map((brand) => ({
            value: brand.id,
            label: brand.title,
          }))
        : []
    );

    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 = [];
      }
    };

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

    const getIdentities = () => {
      ApiServiece.get(`admin/attributes?category_id=${selectedCat.value}`)
        .then((resp) => {
          identities.value = resp.data.data;
          console.log(identities.value, "identities");
        })
        .then(() => {
          localIdentitiesIds.value = localIdentities.value.map(
            (identity) => identity.title
          );

          let hasRepeatedIdentity = false;

          identities.value = identities.value.filter((identity) => {
            if (!localIdentitiesIds.value.includes(identity.title)) {
              return true;
            } else {
              hasRepeatedIdentity = true;
              return false;
            }
          });

          repeatedIdentity.value = hasRepeatedIdentity;

          console.log(repeatedIdentity.value);
        });
    };

    const getAttrebuteValues = () => {
      ApiServiece.get(`admin/attribute-values?attribute_id=1`)
        .then((resp) => {
          console.log(resp, "attrebute values");
          attrebutes.value = resp.data.data;
          console.log("Attributes before filtering:", attrebutes.value);
        })
        .then(() => {
          getProduct();
        })

        .catch((err) => {
          console.log(err);
        });
    };

    const deleteAttribute = (id) => {
      Swal.fire({
        text: `آیا می خواهید این ویژگی را حذف کنید؟`,
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: "بله!",
        cancelButtonText: "خیر",
      }).then((result) => {
        if (result.isConfirmed) {
          ApiServiece.delete(
            `admin/products/${route.params.id}/attributes/${id}`
          )
            .then(() => {
              toast.success("!ویژگی با موفقیت حذف شد", {
                position: "top-right",
                autoClose: 3000,
              });
              locals.value = locals.value.filter((brand) => brand.id !== id);
            })
            .catch((err) => {
              console.log(err);
              toast.error("!مشکلی در حذف کردن ویژگی پیش آمد", {
                position: "top-right",
                autoClose: 3000,
              });
            });
        }
      });
    };

    const deleteIdentity = (id) => {
      Swal.fire({
        text: `آیا می خواهید این مشخصه را حذف کنید؟`,
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: "بله!",
        cancelButtonText: "خیر",
      }).then((result) => {
        if (result.isConfirmed) {
          ApiServiece.delete(
            `admin/products/${route.params.id}/attributes/${id}`
          )
            .then(() => {
              toast.success("!مشخصه با موفقیت حذف شد", {
                position: "top-right",
                autoClose: 3000,
              });
              localIdentities.value = localIdentities.value.filter(
                (identity) => identity.id !== id
              );
            })
            .catch((err) => {
              console.log(err);
              toast.error("!مشکلی در حذف کردن مشخصه پیش آمد", {
                position: "top-right",
                autoClose: 3000,
              });
            });
        }
      });
    };

    const deletImage = (name) => {
      Swal.fire({
        text: `آیا می خواهید این عکس را حذف کنید؟`,
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: "بله!",
        cancelButtonText: "خیر",
      }).then((result) => {
        if (result.isConfirmed) {
          console.log(name);

          ApiServiece.delete(`admin/products/${route.params.id}/images`, {
            headers: {
              Authorization: `Bearer ${localStorage.getItem("token")}`,
            },
            params: {
              fileName: name,
            },
          })
            .then(() => {
              toast.success("!عکس با موفقیت حذف شد", {
                position: "top-right",
                autoClose: 3000,
              });
              images.value = images.value.filter(
                (image) => image.preview !== name
              );
            })
            .catch((err) => {
              console.log(err);
              toast.error("!مشکلی در حذف کردن عکس پیش آمد", {
                position: "top-right",
                autoClose: 3000,
              });
            });
        }
      });
    };

    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, name) => {
      const imageExists = localImages.value.some(
        (image) => image.preview === name
      );

      if (imageExists) {
        deletImage(name);
      } else {
        images.value.splice(index, 1);
      }

      console.log(images.value);
    };

    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);
        files.value.push(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 (!imagePreview.value)
        errors.value.image = "وارد کردن عکس محصول ضروری می باشد";
      if (!description.value)
        errors.value.description = "وارد کردن توضیحات محصول ضروری می باشد";
      if (!productType.value)
        errors.value.productType = "انتخاب حالت محصول ضروری می باشد";

      if (isChosen.value === undefined || isChosen.value === null) {
        errors.value.isChosen = "انتخاب کنید محصول منتخب هست یا خیر";
      }

      if (spescial.value === undefined || spescial.value === null) {
        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 (productType.value != 1 && !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 = identities.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] = "";
    };

    const getProduct = () => {
      ApiServiece.get(`admin/products/${route.params.id}`)
        .then((resp) => {
          categories.value[0].id = resp?.data?.data?.category.id;
          categories.value[0].title = resp?.data?.data?.category.title;
          brands.value[0].id = resp?.data?.data?.brand.id;
          brands.value[0].title = resp?.data?.data?.brand.title;
          productValueId.value = resp.data.data;
          product.value = resp.data.data;
          title.value = product.value?.title;
          slug.value = product.value?.slug;
          summary.value = product.value?.summary;
          description.value = product.value?.description;
          imagePreview.value = product.value?.image;
          productType.value = product.value?.type;
          wholesalePrice.value = product.value?.wholesale_price;
          retailePrice.value = product.value?.retail_price;
          isChosen.value = product.value?.is_chosen;
          chosenPrice.value = product.value?.chosen_price;
          spescial.value = product.value?.is_special;
          spescialPrice.value = product.value?.special_price;
          selectedCat.value = resp?.data?.data?.category.id;
          selectedBrand.value = resp?.data?.data?.brand.id;
          description.value = product.value?.description;

          if (product.value?.special_expires_at) {
            expire.value = moment(
              product.value.special_expires_at,
              "YYYY-MM-DD HH:mm:ss"
            ).format("jYYYY/jMM/jDD HH:mm:ss");
          }

          // if (editor.value) {
          //   quillInstance.value = 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" }],
          //       ],
          //     },
          //   });
          //
          //   quillInstance.value.root.innerHTML = product.value.description;
          //
          //
          //
          //   quillInstance.value.on("text-change", () => {
          //     description.value = quillInstance.value.root.innerHTML;
          //   });
          // }
          selectedBrand.value = product.value?.brand_id;
          selectedCat.value = product.value?.category_id;

          countInCarton.value = product.value?.count_in_carton;

          // Update images
          images.value = product.value.images.map((imageUrl) => ({
            preview: imageUrl,
          }));

          localImages.value = product.value.images.map((imageUrl) => ({
            preview: imageUrl,
          }));

          locals.value = product.value.attribute_value_products.map(
            (productAttribute) => {
              console.log(locals.value, "locals");
              return {
                id: productAttribute.id,
                title: productAttribute.attribute_value.title,
                code: productAttribute.attribute_value.code,
                inventory: productAttribute.inventory,
                attribute_value_id: productAttribute.attribute_value_id,
                isChecked: productAttribute.inventory > 0,
                value: productAttribute.inventory,
              };
            }
          );

          localsIds.value = locals.value.map((attribute) => attribute.code);

          let hasRepeatedAttribute = false;

          attrebutes.value = attrebutes.value.filter((attrebute) => {
            if (!localsIds.value.includes(attrebute.code)) {
              return true;
            } else {
              hasRepeatedAttribute = true;
              return false;
            }
          });

          repeatedAttrebute.value = hasRepeatedAttribute;

          localIdentities.value =
            product.value.solid_attribute_value_products.map(
              (productIdentities) => {
                return {
                  id: productIdentities.id,
                  title: productIdentities.attribute_value.attribute.title,
                  isChecked: true,
                  value: productIdentities.attribute_value.title,
                  attribute_value_id: productIdentities.attribute_value_id,
                };
              }
            );
        })
        .then(() => {
          getIdentities();
        })
        .catch((err) => {
          console.log(err);
        });
    };

    const editAttribute = (id, inventory, attrebuteValueId) => {
      Swal.fire({
        text: "آیا برای ویرایش ویژگی اطمینان دارید؟",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "بله، ویرایش کن",
        cancelButtonText: "لغو",
        reverseButtons: true,
      }).then((result) => {
        if (result.isConfirmed) {
          const formData = new FormData();
          formData.append("inventory", inventory);
          formData.append("attribute_value_id", attrebuteValueId);

          ApiServiece.put(
            `admin/products/${route.params.id}/attributes/${id}`,
            formData
          )
            .then(() => {
              toast.success("!ویژگی با موفقیت ویرایش شد", {
                position: "top-right",
                autoClose: 3000,
              });
            })
            .catch(() => {
              toast.error("!مشکلی در ویرایش ویژگی ایجاد شد", {
                position: "top-right",
                autoClose: 3000,
              });
            });
        }
      });
    };

    const editIdentity = (id, title, valueID) => {
      Swal.fire({
        text: "آیا برای ویرایش مشخصه اطمینان دارید؟",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "بله، ویرایش کن",
        cancelButtonText: "لغو",
        reverseButtons: true,
      }).then((result) => {
        if (result.isConfirmed) {
          const formData = new FormData();

          formData.append("attribute_id", id);
          formData.append("title", title);
          ApiServiece.put(`admin/attribute-values/:${valueID}`, formData)
            .then(() => {
              toast.success("!مشخصه با موفقیت ویرایش شد", {
                position: "top-right",
                autoClose: 3000,
              });
            })
            .catch(() => {
              toast.error("!مشکلی در ویرایش مشخصه ایجاد شد", {
                position: "top-right",
                autoClose: 3000,
              });
            });
        }
      });
    };

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

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

      loading.value = true;

      const formData = new FormData();
      formData.append("_method", "put");
      formData.append("title", title.value);
      formData.append("slug", slug.value);
      formData.append("summary", summary.value);
      formData.append("description", description.value);

      if (productType.value == 2 || productType.value == 3) {
        formData.append("count_in_carton", countInCarton.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 (spescial.value == 1 && isChosen.value == 0) {
        if (spescialPrice.value) {
          formData.append("special_price", parseInt(spescialPrice.value, 10));
        }

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

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

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

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

      formData.append("brand_id", selectedBrand.value);
      formData.append("category_id", selectedCat.value);
      if (image.value) {
        formData.append("image", image.value);
      }

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

      ApiServiece.post(`admin/products/${route.params.id}`, formData, {
        headers: {
          "content-type": "multipart",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      })
        .then((resp) => {
          loading.value = false;
          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);
          if (selectedAttributes.value.length > 0) {
            console.log(selectedAttributes.value);
            ApiServiece.post(
              `admin/products/${route.params.id}/attributes`,
              jsonString
            );
          }

          selectedidentities.value = identities.value
            .filter((identity) => identity.isChecked)
            .map((identity) => ({
              attribute_id: identity.id,
              attribute_value_title: identity.value,
            }));
          if (selectedidentities.value.length > 0) {
            const finalPayload = {
              productSolidAttributes: selectedidentities.value,
            };
            const jsonString = JSON.stringify(finalPayload, null, 2);
            ApiServiece.post(
              `admin/products/${route.params.id}/solid-attributes`,
              jsonString
            );
          }

          if (files.value.length > 0) {
            console.log(files.value);

            imagesTosend.value = images.value.filter((image) => {
              return !localImages.value.some(
                (localImage) => localImage.preview === image.preview
              );
            });

            // Collect all promises
            const uploadPromises = imagesTosend.value.map((image) => {
              const formData = new FormData();
              formData.append("image", image.file);

              return ApiServiece.post(
                `admin/products/${route.params.id}/images`,
                formData,
                {
                  headers: {
                    "content-type": "multipart",
                    Authorization: `Bearer ${localStorage.getItem("token")}`,
                  },
                }
              );
            });

            // Wait for all uploads to finish
            Promise.all(uploadPromises)
              .then((responses) => {
                console.log("All images uploaded:", responses);
                loading.value = false;
                toast.success("!محصول با موفقیت ویرایش شد", {
                  position: "top-right",
                  autoClose: 1000,
                });
              })
              .catch((error) => {
                console.error("Error uploading images:", error);
                loading.value = false;
                toast.error("خطایی در بارگذاری تصاویر رخ داد", {
                  position: "top-right",
                  autoClose: 1000,
                });
              });
          } else {
            toast.success("!محصول با موفقیت ویرایش شد", {
              position: "top-right",
              autoClose: 1000,
            });
          }
        })

        .catch((error) => {
          loading.value = false;
          console.error(error);
          toast.error("!مشکلی در ویرایش محصول ایحاد شد", {
            position: "top-right",
            autoClose: 1000,
          });
        });
    };

    return {
      title,
      slug,
      summary,
      editor,
      categories,
      errors,
      image,
      imagePreview,
      handleImageChange,
      removeImage,
      submitForm,
      clearError,
      editorContent,
      author,
      blogCat,
      loading,
      productType,
      isChosen,
      spescial,
      date,
      selectedCat,
      brands,
      selectedBrand,
      attrebutes,
      images,
      addImage,
      handleImageUpload,
      description,
      onCheckboxChange,
      retailePrice,
      wholesalePrice,
      spescialPrice,
      chosenPrice,
      expire,

      selectedAttributes,
      selectedidentities,
      locals,
      editAttribute,
      deleteAttribute,
      deletImage,
      countInCarton,
      localIdentities,
      deleteIdentity,
      identities,
      handleAttributeUpdated,
      editIdentity,
      repeatedIdentity,
      repeatedAttrebute,
      categorySelectorLoader,
      formattedCategories,
      formattedBrands,
      brandSelectorLoader,
      handleSearch,
      handleBrandSearch,
      productImageRef
    };
  },
};
</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>
