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

              <BCol md="6" v-if="blogType == 2 || blogType == 3">
                <div class="form-group">
                  <label class="form-label">قیمت (عمده) </label>
                  <input
                    type="text"
                    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 v-if="blogType == 1 || blogType == 3" md="6">
                <div class="form-group">
                  <label class="form-label">قیمت (تک) </label>
                  <input
                    type="text"
                    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 md="6">
                <div class="form-group">
                  <label class="form-label">منتخب</label>
                  <select
                    :class="{ 'is-invalid': errors.isChosen }"
                    v-model="isChosen"
                    class="form-control"
                    @input="clearError('isChosen')"
                  >
                    <option value="" disabled selected>
                      انتخاب حالت منتخب
                    </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="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>
                  <select
                    :class="{ 'is-invalid': errors.spescial }"
                    v-model="spescial"
                    class="form-control"
                  >
                    <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="text"
                    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>

                  <VueDatePicker
                    :format="'yyyy-MM-dd HH:mm:ss'"
                    v-model="date"
                  ></VueDatePicker>
                </div>
                <small v-if="errors.spescial" class="text-danger">
                  {{ errors.spescial }}
                </small>
              </BCol>

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

              <BCard>
                <div class="card-header">
                  <h5 class="mb-0">اضافه کردن ویژگی ها</h5>
                </div>
                <BRow class="g-3 mt-2">
                  <!-- 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"
                            />
                          </BCol>
                          <small
                            v-if="errors[attrebute.id]"
                            class="text-danger"
                          >
                            {{ errors[attrebute.id] }}
                          </small>
                        </label>
                      </div>
                    </div>
                  </BCol>
                </BRow>

                <!-- Submit Button -->
                <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>
              </BCard>

              <BCard>
                <div class="card-header">
                  <h5 class="mb-0">اضافه کردن عکس ها</h5>
                </div>
                <BRow class="g-3 mt-2">
                  <BCol
                    v-for="(image, index) in images"
                    :key="index"
                    class="mb-3"
                    md="6"
                  >
                    <div class="form-group">
                      <label class="form-label">تصویر محصول</label>

                      <input
                        type="file"
                        accept="image/*"
                        @change="(event) => handleImageChange(event, index)"
                        class="form-control"
                      />

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

                <!-- Add New Image Upload Section -->
                <div class="text-center mt-3">
                  <button @click="addImage" class="btn btn-primary">
                    افزودن عکس جدید
                  </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>
        </BCard>
      </BCol>
    </BRow>
  </Layout>
</template>

<script>
import Swal from "sweetalert2";
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import ApiServiece from "@/services/ApiService";
import { ref, onMounted } from "vue";
import Layout from "@/layout/custom.vue";
import VueDatePicker from "@vuepic/vue-datepicker";
import "@vuepic/vue-datepicker/dist/main.css";

export default {
  name: "SAMPLE-PAGE",
  components: {
    Layout,
    VueDatePicker,
  },
  setup() {
    const selectedAttrebutes = ref([
      {
        inventory: null,
        type: null,
        attribute_value_id: null,
      },
    ]);
    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 selectedTag = ref();
    const date = ref();
    const spescial = ref();
    const isChosen = ref();
    const blogType = 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 getBrands = () => {
      ApiServiece.get(`admin/brands`)
        .then((resp) => {
          brands.value = resp.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    };

    const getAttrebuteValues = () => {
      ApiServiece.get(`admin/attribute-values`)
        .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);
    };

    // Handle Image Change
    const removeImage = (index) => {
      images.value.splice(index, 1);
      errors.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 (!blogCat.value)
        errors.value.blogCat = "انتخاب دسته برای محصول ضروری می باشد";
      if (!editorContent.value)
        errors.value.editorContent = "وارد کردن محتوای محصول ضروری می باشد";
      if (!image.value)
        errors.value.image = "وارد کردن عکس محصول ضروری می باشد";
      if (!description.value)
        errors.value.description = "وارد کردن توضیحات محصول ضروری می باشد";
      if (!blogType.value)
        errors.value.blogType = "انتخاب حالت محصول ضروری می باشد";
      if (!isChosen.value)
        errors.value.isChosen = "انتخاب کنید محصول منتخب هست یا خیر";
      if (!spescial.value)
        errors.value.spescial = "انتخاب کنید محصول ویژه هست یا خیر";
      if (!retailePrice.value)
        errors.value.retailePrice = "قیمت محصول تک را وارد نمایید";
      if (!wholesalePrice.value)
        errors.value.wholesalePrice = "قیمت محصول عمده را وارد نمایید";
      if (!spescialPrice.value)
        errors.value.spescialPrice = "تخفیف محصول ویژه را وارد کنید";
      if (!chosenPrice.value)
        errors.value.chosenPrice = "تخفیف محصول منتخب را وارد کنید";
      if (!expire.value)
        errors.value.expire = "تاریخ انقضای محصول ویژه را انتخاب نمایید";

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

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

    onMounted(() => {
      getCats();
      getBrands();
      getAttrebuteValues();
    });

    const submitForm = () => {
      const selectedAttributes = attrebutes.value
        .filter((attribute) => {
          return attribute.isChecked;
        })
        .map((attribute) => ({
          attribute_value_id: attribute.id,
          inventory: attribute.value,
        }));
      console.log(selectedAttributes);
      console.log(errors);
      if (!validateForm()) 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("content", editorContent.value);
      formData.append("image", image.value);
      formData.append("author", author.value);
      formData.append("blog_category_id", blogCat.value);

      ApiServiece.post(`admin/blogs`, formData, {
        headers: {
          "content-type": "multipart",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      })
        .then((resp) => {
          console.log(resp);
          toast.success("!بلاگ با موفقیت اضافه شد", {
            position: "top-right",
            autoClose: 1000,
          });
        })

        .catch((error) => {
          console.error(error);
          Swal.fire({
            icon: "error",
            title: "خطا",
            text: `!افزودن بلاگ با مشکل مواجه شد: ${
              error.response?.data?.message || "خطای غیرمنتظره رخ داد."
            }`,
          });
        })
        .finally(() => {
          loading.value = false;
        });
    };

    return {
      title,
      slug,
      summary,
      editor,
      cats,
      errors,
      image,
      imagePreview,
      handleImageChange,
      removeImage,
      submitForm,
      clearError,
      editorContent,
      author,
      blogCat,
      loading,
      blogType,
      isChosen,
      spescial,
      date,
      selectedTag,
      brands,
      selectedBrand,
      attrebutes,
      images,
      addImage,
      handleImageUpload,
      selectedAttrebutes,
      description,
      onCheckboxChange,
      retailePrice,
      wholesalePrice,
      spescialPrice,
      chosenPrice,
      expire,
    };
  },
};
</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;
  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>
