<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="میزان سفارش"
                    :class="{ 'is-invalid': errors.minOrder }"
                    @input="clearError('minOrder')"
                  />
                </div>
                <small v-if="errors.minOrder" class="text-danger">
                  {{ errors.minOrder }}
                </small>
              </BCol>

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

              <BCol md="6">
                <div class="form-group">
                  <label class="form-label">اعمال تخفیف بر</label>
                  <select
                    v-model="whichPart"
                    class="form-control"
                    :class="{ 'is-invalid': errors.whichPart }"
                    @select="clearError('whichPart')"
                    placeholder="انتخاب محل اعمل تخفیف"
                  >
                    <option value="cat">دسته</option>
                    <option value="product">محصول</option>
                    <option value="all">همه</option>
                  </select>
                </div>
                <small v-if="errors.discountType" class="text-danger">
                  {{ errors.discountType }}
                </small>
              </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"
                    placeholder="دسته ای را انتخاب کنید"
                  />
                </div>
                <small v-if="errors.selectedCat" class="text-danger">
                  {{ errors.selectedCat }}
                </small>
              </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="categorySelectorLoader"
                    v-model="selectedProduct"
                    :options="formattedProducts"
                    placeholder="محصولی را انتخاب کنید "
                  />
                </div>
                <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"
                    @input="handleStartDateInput"
                  ></DatePicker>
                </div>
                <small v-if="errors.startDate" class="text-danger">
                  {{ errors.startDate }}
                </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="expire"
                    @input="handleExpireDateInput"
                  ></DatePicker>
                </div>
                <small v-if="errors.expire" class="text-danger">
                  {{ errors.expire }}
                </small>
              </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([]);
    const errors = ref({});
    const products = ref();
    const discount = ref();

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

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

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

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

    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;
          selectedCat.value = discount.value.category_id;
          if (discount.value.category_id) {
            whichPart.value = "cat";
          }

          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";
          }

          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(() => {
      getCats();
      getProduct();
      getDiscount();
    });

    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);
      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);
      }

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

      ApiServiece.post(`/admin/discounts`, 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,
    };
  },
};
</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>
