<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>

              <!-- Second Input Field (Slug) -->
              <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"
                    v-model="selectedCat"
                    :options="formattedCategories" 
                    label="label"
                    :reduce="(option) => option.value"
                    placeholder="دسته ای را انتخاب کنید"
                    @search="handleSearch"
                  />
                </div>
              </BCol>

              <BCol v-if="whichPart === 'product'" md="6">
                <div class="form-group">
                  <label class="form-label">محصول</label>
                  <VueSelect
                    style="--vs-min-height: 48px; --vs-border-radius: 8px"
                    :isLoading="productSelectorLoader"
                    v-model="selectedProduct"
                    :options="formattedProducts"
                    @search="handleProductSearch"
                    placeholder="محصولی را انتخاب کنید "
                  />
                </div>
              </BCol>

              <BCol md="6">
                <div class="form-group">
                  <label class="form-label"> تاریخ اعمال تخفیف </label>

                  <DatePicker
                    :format="'jYYYY/jMM/jDD HH:mm:ss'"
                    type="datetime"
                    clearable
                    v-model="startDate"
                    @input="handleStartDateInput"
                  ></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"
                    clearable
                    v-model="expire"
                    @input="handleExpireDateInput"
                  ></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 { useRoute } from "vue-router";
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import ApiServiece from "@/services/ApiService";
import { ref, onMounted, 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 route = useRoute();
    const title = ref();
    const discountType = ref();
    const amount = ref();
    const minOrder = ref();
    const selectedCat = ref();
    const selectedProduct = ref();
    const startDate = ref();
    const expire = ref();
    const maxUsage = ref();
    const whichPart = ref();
    const loading = ref(false);
    const categories = ref([{ id: null, title: "" }]);
    const errors = ref({});
    const products = ref([{ id: null, title: "" }]);
    const discount = ref();
    const categorySelectorLoader = ref(false);
    const productSelectorLoader = ref(false);

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

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

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

    const 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 getDiscount = () => {
      ApiServiece.get(`admin/discounts/${route.params.id}`)
        .then((resp) => {
          discount.value = resp.data.data;
          title.value = discount.value.title;
          discountType.value = discount.value.type;
          amount.value = discount.value.amount;
          minOrder.value = discount.value.min_order;

          if (discount.value.category_id) {
            whichPart.value = "cat";
            categories.value[0].id = discount.value.category?.id;
            categories.value[0].title = discount.value.category?.title;
            selectedCat.value = discount.value.category_id;
          }

          if (!discount.value.category_id && !discount.value.product_id) {
            whichPart.value = "all";
          }

          selectedProduct.value = discount.value.product_id;
          if (discount.value.product_id) {
            whichPart.value = "product";
            products.value[0].id = discount.value.product?.id;
            products.value[0].title = discount.value.product?.title;
            selectedProduct.value = discount.value.product_id;
          }

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

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

          maxUsage.value = discount.value.max_usage;
        })
        .catch((err) => {
          console.log(err);
        });
    };

    const handleStartDateInput = () => {
      if (startDate.value) {
        startDate.value = moment(
          startDate.value,
          "jYYYY/jMM/jDD HH:mm:ss"
        ).format("YYYY-MM-DD HH:mm:ss");
      } else {
        clearError("expire");
      }
    };

    const handleExpireDateInput = () => {
      if (expire.value) {
        expire.value = moment(expire.value, "jYYYY/jMM/jDD HH:mm:ss").format(
          "YYYY-MM-DD HH:mm:ss"
        );
      } else {
        clearError("expire");
      }
    };

    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 (!startDate.value)
      //   errors.value.startDate = "انتخاب تاریخ اعمال تخفیف الزامی می باشد ";
      //
      // if (!whichPart.value)
      //   errors.value.whichPart = "مشخص کنید تخفیف بر چه بخشی اعمال شود";
      return Object.keys(errors.value).length === 0;
    };

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

    onMounted(() => {
      getDiscount();

      handleProductSearch()
      handleSearch()
    });

    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.put(`/admin/discounts/${route.params.id || discount.value?.id}`, formData)
        .then((resp) => {
          loading.value = false;
          toast.success("!تخفیف با موفقیت ویرایش شد", {
            position: "top-right",
            autoClose: 1000,
          });
          console.log(resp);
        })
        .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,
      handleStartDateInput,
      handleExpireDateInput,
      whichPart,
      clearError,
      loading,
      formattedCategories,
      formattedProducts,
      handleSearch,
      handleProductSearch,
    };
  },
};
</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>
