<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>
                  <select
                    v-model="discountType"
                    class="form-control"
                    :class="{ 'is-invalid': errors.discountType }"
                    @change="clearError('discountType')"
                    placeholder="انتخاب نوع تخفیف"
                  >
                    <option value="percentage">درصدی</option>
                    <option value="const">مبلغ ثابت</option>
                  </select>
                </div>
                <small v-if="errors.discountType" class="text-danger">
                  {{ errors.discountType }}
                </small>
              </BCol>

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

              <BCol md="6">
                <div class="form-group">
                  <label class="form-label">حداقل میزان سفارش</label>
                  <input
                    v-model="minOrder"
                    class="form-control"
                    type="number"
                    placeholder="میزان سفارش"
                  />
                </div>
              </BCol>

              <BCol md="6">
                <div class="form-group">
                  <label class="form-label">حداکثر میزان اسفاده</label>
                  <input
                    v-model="maxUsage"
                    type="number"
                    class="form-control"
                    placeholder="حداکثر میزان استفاده"
                  />
                </div>
              </BCol>

              <BCol md="6">
                <div class="form-group">
                  <label class="form-label">اعمال تخفیف بر</label>
                  <select
                    v-model="whichPart"
                    class="form-control"
                    placeholder="انتخاب محل اعمال تخفبف"
                  >
                    <option value="cat">دسته</option>
                    <option value="product">محصول</option>
                    <option value="all">همه</option>
                  </select>
                </div>
              </BCol>

              <BCol v-if="whichPart === 'cat'" md="6">
                <div class="form-group">
                  <label class="form-label">دسته</label>

                  <VueSelect
                    style="--vs-min-height: 48px; --vs-border-radius: 8px"
                    :isLoading="categorySelectorLoader"
                    v-model="selectedCat"
                    :options="formattedCategories"
                    @change="clearError('selectedCat')"
                    placeholder="دسته ای را انتخاب کنید"
                    @search="handleSearch"
                  />
                </div>
                <small v-if="errors.selectedCat" class="text-danger">
                  {{ errors.selectedCat }}
                </small>
              </BCol>

              <BCol
                v-if="whichPart === 'product'"
                sm="6"
                class="mt-3"
                style="margin-top: 30px"
              >
                <label for="token" style="margin-bottom: 5px">
                  انتخاب محصول
                </label>

                <VueSelect
                  style="--vs-min-height: 48px; --vs-border-radius: 8px"
                  :isLoading="categorySelectorLoader"
                  v-model="selectedProduct"
                  :options="formattedProducts"
                  @search="handleProductSearch"
                  @change="clearError('selectedProduct')"
                  placeholder="محصولی را انتخاب کنید"
                />
                <small v-if="errors.selectedProduct" class="text-danger">
                  {{ errors.selectedProduct }}
                </small>
              </BCol>

              <BCol md="6">
                <div class="form-group">
                  <label class="form-label"> تاریخ اعمال تخفیف </label>
                  <DatePicker
                    :format="'jYYYY/jMM/jDD HH:mm:ss'"
                    type="datetime"
                    v-model="startDate"
                    clearable
                  ></DatePicker>
                </div>
              </BCol>

              <BCol md="6">
                <div class="form-group">
                  <label class="form-label"> تاریخ انقضای تخفیف </label>
                  <DatePicker
                    :format="'jYYYY/jMM/jDD HH:mm:ss'"
                    type="datetime"
                    v-model="expire"
                    clearable
                  ></DatePicker>
                </div>
              </BCol>
            </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 VueSelect from "vue3-select-component";
import moment from "jalali-moment";
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import ApiServiece from "@/services/ApiService";
import { ref, computed } from "vue";
import Layout from "@/layout/custom.vue";
import DatePicker from "vue3-persian-datetime-picker";

export default {
  name: "SAMPLE-PAGE",
  components: {
    Layout,
    DatePicker,

    VueSelect,
  },
  setup() {
    const productSelectorLoader = ref(false);
    const title = ref();
    const discountType = ref();
    const amount = ref();
    const minOrder = ref(null);
    const selectedCat = ref();
    const selectedProduct = ref();
    const startDate = ref();
    const expire = ref();
    const maxUsage = ref(null);
    const whichPart = ref();
    const loading = ref(false);
    const categories = ref([]);
    const errors = ref({});
    const products = ref();
    const categorySelectorLoader = ref(false);

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

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

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

    const formattedProducts = computed(() =>
      Array.isArray(products.value)
        ? products.value.map((product) => ({
            value: product.id,
            label: product?.translation?.title,
          }))
        : []
    );

    const validateForm = () => {
      errors.value = {};
      if (!title.value) errors.value.title = "وارد کردن عنوان تخفیف الزامی است";
      if (!discountType.value)
        errors.value.discountType = "وارد کردن حالت تخفیف الزامی است";
      if (!amount.value)
        errors.value.amount = "وارد کردن مقدار تخفیف الزامی می باشد";

      // if (!selectedCat.value && whichPart.value === "cat")
      //   errors.value.selectedCat = "انتخاب دسته برای تخفیف الزامی می باشد";
      // if (!selectedProduct.value && whichPart.value === "product")
      //   errors.value.selectedProduct = "انتخاب محصول برای تخفیف الزامی می باشد";
      //
      //
      // if (!whichPart.value)
      //   errors.value.whichPart = "مشخص کنید تخفیف بر چه بخشی اعمال شود";
      return Object.keys(errors.value).length === 0;
    };

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

    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("type", discountType.value);
      formData.append("amount", amount.value);
      if(minOrder.value)
        formData.append("min_order", minOrder.value);

      if (whichPart.value === "cat") {
        formData.append("category_id", selectedCat.value);
      }

      if (whichPart.value === "product") {
        formData.append("product_id", selectedProduct.value);
      }

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

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

      if (maxUsage.value)
        formData.append("max_usage", maxUsage.value);

      ApiServiece.post(`/admin/discounts`, formData)
        .then(() => {
          loading.value = false;
          toast.success("!تخفیف با موفقیت اضافه شد", {
            position: "top-right",
            autoClose: 1000,
          });

          // Clear form fields after successful submission
          title.value = "";
          discountType.value = "";
          amount.value = "";
          minOrder.value = "";
          whichPart.value = "";
          selectedCat.value = null;
          selectedProduct.value = null;
          startDate.value = "";
          expire.value = "";
          maxUsage.value = "";
        })
        .catch((error) => {
          loading.value = false;
          console.log(error.response.message);
          toast.error(`${error.response.data.message}`, {
            position: "top-right",
            autoClose: 1000,
          });
        });
    };

    return {
      categories,
      errors,
      title,
      products,
      discountType,
      amount,
      minOrder,
      selectedCat,
      selectedProduct,
      startDate,
      expire,
      maxUsage,
      submitForm,
      whichPart,
      clearError,
      loading,

      handleSearch,
      categorySelectorLoader,
      formattedCategories,
      handleProductSearch,
      productSelectorLoader,
      formattedProducts,
    };
  },
};
</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;
}
.custom-select {
}
</style>
