<template>
  <Layout>
    <BRow>
      <BCol sm="12">
        <BCard no-body>
          <BCardHeader>
            <div class="d-flex justify-content-between align-items-center">
              <h5>ویرایش بنر</h5>

              <!-- Help and Modal buttons -->
              <div>
                <button
                  v-if="pageType === 'main_page'"
                  data-bs-toggle="modal"
                  data-bs-target="#mainPageBanner"
                  class="btn btn-info btn-sm mx-2"
                  @click="showHelp"
                >
                  <i class="fa fa-question-circle"></i> راهنمایی بنر صفحه اصلی
                </button>
                <button
                  data-bs-toggle="modal"
                  data-bs-target="#catBanner"
                  class="btn btn-info btn-sm mx-2"
                  @click="showModal"
                  v-if="pageType === 'category'"
                >
                  <i class="fa fa-info-circle"></i> راهنمایی بنر دسته ها
                </button>
                <button
                  data-bs-toggle="modal"
                  data-bs-target="#specialPageBanner"
                  class="btn btn-info btn-sm mx-2"
                  @click="showModal"
                  v-if="pageType === 'special_page'"
                >
                  <i class="fa fa-info-circle"></i> راهنمایی بنر فروش ویژه
                </button>
                <button
                    data-bs-toggle="modal"
                    data-bs-target="#specialPageBanner"
                    class="btn btn-info btn-sm mx-2"
                    @click="showModal"
                    v-if="pageType === 'blog_page'"
                >
                  <i class="fa fa-info-circle"></i>ر راهنمایی بنر بلاگ
                </button>
                <button
                  v-if="pageType === 'brand'"
                  data-bs-toggle="modal"
                  data-bs-target="#brandBanner"
                  class="btn btn-info btn-sm mx-2"
                  @click="showModal"
                >
                  <i class="fa fa-info-circle"></i> راهنمایی بنر برند
                </button>
              </div>
            </div>
          </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
                    class="form-select"
                    aria-label="Default select example"
                    v-model="pannel"
                    @change="clearError('pannel')"
                    :class="{ 'is-invalid': errors.pannel }"
                    placeholder="انخاب پنل"
                  >
                    <option value="wholesale">پنل عمده فروشی</option>
                    <option value="web">وب سایت و اپلیکیشن</option>
                  </select>
                </div>
                <small v-if="errors.pannel" class="text-danger">
                  {{ errors.pannel }}
                </small>
              </BCol>

              <BCol v-if="pannel === 'web' && pannel" md="6">
                <div class="form-group">
                  <label class="form-label">نمایش در</label>
                  <select
                    v-model="pageType"
                    :class="{ 'is-invalid': errors.pageType }"
                    class="form-select"
                    aria-label="Default select example"
                    @change="clearError('pageType')"
                    placeholder="انخاب صفحه اصلی"
                  >
                    <option value="main_page">صفحه اصلی</option>
                    <option value="category">صفحه دسته</option>
                    <option value="special_page">صفحه فروش ویژه</option>
                    <option value="brand">صفحه برند</option>
                    <option value="blog_page">صفحه بلاگ</option>
                  </select>
                </div>
                <small v-if="errors.pageType" class="text-danger">
                  {{ errors.pageType }}
                </small>
              </BCol>

              <BCol v-if="pageType === 'category' && pannel === 'web'" md="6">
                <div class="form-group">
                  <label class="form-label">صفحه دسته</label>

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

              <BCol v-if="pageType === 'brand' && pannel === 'web'" md="6">
                <div class="form-group">
                  <label class="form-label">صفحه برند</label>

                  <VueSelect
                    style="--vs-min-height: 48px; --vs-border-radius: 8px"
                    v-model="selectedBrandPage"
                    label="label"
                    :isLoading="brandSelectorLoader"
                    :reduce="(option) => option.value"
                    :options="formattedBrands"
                    @change="clearError(`selectedBrandPage`)"
                    placeholder="برندی را انتخاب کنید"
                    @search="handleBrandSearch"
                  />
                </div>
                <small v-if="errors.selectedBrandPage" class="text-danger">
                  {{ errors.selectedBrandPage }}
                </small>
              </BCol>

              <BCol v-if="pannel == 'web' && pannel" md="6">
                <div class="form-group">
                  <label class="form-label">انتخاب صفحه فرود</label>
                  <select
                    class="form-select"
                    aria-label="Default select example"
                    v-model="landingType"
                    @change="clearError('landingType')"
                    :class="{ 'is-invalid': errors.landingType }"
                    placeholder="انتخاب صفحه فرود"
                  >
                    <option value="product">صفحه محصولات</option>
                    <option value="cat">صفحه دسته ها</option>
                  </select>
                </div>
                <small v-if="errors.landingType" class="text-danger">
                  {{ errors.landingType }}
                </small>
              </BCol>

              <BCol
                v-if="landingType === 'product'"
                sm="6"
                class="mt-3"
                style="margin-top: 30px"
              >
                <label for="token">صفحه کدام محصول</label>

                <VueSelect
                  style="
                    --vs-min-height: 48px;
                    --vs-border-radius: 8px;
                    margin-top: 7px;
                  "
                  v-model="selectedLandingProduct"
                  :reduce="(option) => option.value"
                  label="label"
                  :isLoading="productSelectorLoader"
                  :options="formattedProducts"
                  @search="handleProductSearch"
                  placeholder="محصولی را انتخاب کنید"
                />
                <small v-if="errors.selectedLandingProduct" class="text-danger">
                  {{ errors.selectedLandingProduct }}
                </small>
              </BCol>

              <BCol v-if="landingType === 'cat'" md="6">
                <div class="form-group">
                  <label class="form-label">صفحه کدام دسته </label>

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

              <BCol v-if="pageType === 'main_page' && pannel === 'web'" md="6">
                <div class="form-group">
                  <label class="form-label">موقعیت در صفحه اصلی</label>
                  <select
                    class="form-select"
                    aria-label="Default select example"
                    v-model="selectedLoc"
                    @change="clearError('selectedLoc')"
                    :class="{ 'is-invalid': errors.selectedLoc }"
                    placeholder="موقعیت بنر"
                  >
                    <option value="A">َA-Slideshow</option>
                    <option value="B">B-Banner</option>
                    <option value="C">C-Banner</option>
                    <option value="D">D-Banner</option>
                    <option value="E">E-Banner</option>
                    <option value="F">F-Banner</option>
                    <option value="G">G-Banner</option>
                    <option value="H">H-Banner</option>
                    <option value="I">I-Banner</option>
                    <option value="J">J-Banner</option>
                  </select>
                </div>
                <small v-if="errors.selectedLoc" class="text-danger">
                  {{ errors.selectedLoc }}
                </small>
              </BCol>

              <BCol v-if="pageType === 'category' && pannel === 'web'" md="6">
                <div class="form-group">
                  <label class="form-label">موقعیت در صفحه دسته ها</label>
                  <select
                    class="form-select"
                    aria-label="Default select example"
                    v-model="selectedLoc"
                    @change="clearError('selectedLoc')"
                    :class="{ 'is-invalid': errors.selectedLoc }"
                    placeholder="موقعیت بنر"
                  >
                    <option value="A">َA-Slideshow</option>
                    <option value="B">B-Banner</option>
                    <option value="C">C-Banner</option>
                    <option value="D">D-Banner</option>
                    <option value="E">E-Banner</option>
                    <option value="F">F-Banner</option>
                    <option value="G">G-Banner</option>
                    <option value="H">H-Banner</option>
                    <option value="I">I-Banner</option>
                  </select>
                </div>
                <small v-if="errors.selectedLoc" class="text-danger">
                  {{ errors.selectedLoc }}
                </small>
              </BCol>

              <BCol
                v-if="pageType === 'special_page' && pannel === 'web'"
                md="6"
              >
                <div class="form-group">
                  <label class="form-label">موقعیت در صفحه فروش ویژه</label>
                  <select
                    class="form-select"
                    aria-label="Default select example"
                    v-model="selectedLoc"
                    @change="clearError('selectedLoc')"
                    :class="{ 'is-invalid': errors.selectedLoc }"
                    placeholder="موقعیت بنر"
                    :value="(selectedLoc = 'A')"
                  >
                    <option value="A">A-Slideshow</option>
                  </select>
                </div>
                <small v-if="errors.selectedLoc" class="text-danger">
                  {{ errors.selectedLoc }}
                </small>
              </BCol>

              <BCol v-if="pageType === 'brand' && pannel === 'web'" md="6">
                <div class="form-group">
                  <label class="form-label">موقعیت در صفحه برند</label>
                  <select
                    class="form-select"
                    aria-label="Default select example"
                    v-model="selectedLoc"
                    @change="clearError('selectedLoc')"
                    :class="{ 'is-invalid': errors.selectedLoc }"
                    placeholder="موقعیت بنر"
                  >
                    <option value="A">َA-Slideshow</option>
                    <option value="B">B-Banner</option>
                    <option value="C">C-Banner</option>
                    <option value="D">D-Banner</option>
                    <option value="E">E-Banner</option>
                    <option value="F">F-Banner</option>
                    <option value="G">G-Banner</option>
                    <option value="H">H-Banner</option>
                    <option value="I">I-Banner</option>
                    <option value="J">J-Banner</option>
                  </select>
                </div>
                <small v-if="errors.selectedLoc" class="text-danger">
                  {{ errors.selectedLoc }}
                </small>
              </BCol>

              <BCol
                  v-if="pageType === 'blog_page' && pannel === 'web'"
                  md="6"
              >
                <div class="form-group">
                  <label class="form-label">موقعیت در صفحه بلاگ</label>
                  <select
                      class="form-select"
                      aria-label="Default select example"
                      v-model="selectedLoc"
                      @change="clearError('selectedLoc')"
                      :class="{ 'is-invalid': errors.selectedLoc }"
                      placeholder="موقعیت بنر"
                      :value="(selectedLoc = 'A')"
                  >
                    <option value="A">A-Banner</option>
                  </select>
                </div>
                <small v-if="errors.selectedLoc" class="text-danger">
                  {{ errors.selectedLoc }}
                </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.imagePreview }"
                  />

                  <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.imagePreview" class="text-danger">
                    {{ errors.imagePreview }}
                  </small>
                </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>

    <mainPageBanner />
    <catBanner />
    <specialBanner />
    <brandBanner />
  </Layout>
</template>

<script>
import VueSelect from "vue3-select-component";
import { useRoute } from "vue-router";
import catBanner from "@/components/modals/helperModals/catBanner.vue";
import mainPageBanner from "@/components/modals/helperModals/mainPageBanner.vue";
import specialBanner from "@/components/modals/helperModals/specialBanner.vue";
import brandBanner from "@/components/modals/helperModals/brandBanner.vue";
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";

export default {
  name: "SAMPLE-PAGE",
  components: {
    Layout,
    mainPageBanner,
    catBanner,
    VueSelect,
    specialBanner,
    brandBanner,
  },
  setup() {
    const route = useRoute();
    const title = ref();
    const pageType = ref();
    const products = ref([{ id: null, title: "" }]);
    const brands = ref([{ id: null, title: "" }]);
    const cats = ref([{ id: null, title: "" }]);
    const catPages = ref([{ id: null, title: "" }]);
    const landingType = ref();
    const selectedCatPage = ref();
    const selectedLandingCat = ref();
    const selectedLandingProduct = ref();
    const selectedLoc = ref();
    const pannel = ref();
    const image = ref();
    const imagePreview = ref();
    const selectedBrandPage = ref();
    const loading = ref(false);
    const errors = ref({});

    const categorySelectorLoader = ref(false);
    const productSelectorLoader = ref(false);
    const categoryPageSelectorLoader = ref(false);
    const brandSelectorLoader = ref(false);

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

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

    const formattedProducts = computed(() =>
      Array.isArray(products.value)
        ? products.value.map((product) => ({
            value: product.id,
            label: product.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 formattedCatPages = computed(() =>
      Array.isArray(catPages.value)
        ? catPages.value.map((catPage) => ({
            value: catPage.id,
            label: catPage.title,
          }))
        : []
    );

    const handleCategoryPageSearch = async (searchTerm) => {
      if (searchTerm.length < 3) return;
      categoryPageSelectorLoader.value = true;
      try {
        const response = await ApiServiece.get(
          `admin/categories/parents?title=${searchTerm}`
        );
        catPages.value = response.data.data;
        categoryPageSelectorLoader.value = false;
      } catch (error) {
        categoryPageSelectorLoader.value = false;
        catPages.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 = [];
      }
    };

    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 (!pageType.value)
        errors.value.pageType = "مشخص کنید بنر کجا نشان داده شود";
      if (pageType.value === "category" && !selectedCatPage.value)
        errors.value.selectedCatPage = "صفحه دسته را انتخاب کنید";
      if (pageType.value === "brand" && !selectedBrandPage.value)
        errors.value.selectedBrandPage = "صفحه برند را انتخاب کنید";
      if (!landingType.value)
        errors.value.landingType = "صفحه فرود را انتخاب نمایید";
      if (landingType.value === "cat" && !selectedLandingCat.value)
        errors.value.selectedLandingCat = "صفحه فرود دسته را انتخاب کنید";
      if (landingType.value === "product" && !selectedLandingProduct.value)
        errors.value.selectedLandingProduct = "صفحه فرود محصول را انتخاب کنید";

      if (!selectedLoc.value)
        errors.value.selectedLoc = "موقعیت بنر را انتخاب کنید";

      if (!pannel.value) errors.value.pannel = "پنل نمایش بنر را انتخاب کنید";

      if (!imagePreview.value)
        errors.value.imagePreview = "عکس بنر را وارد نمایید";

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

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

    const getBanner = () => {
      ApiServiece.get(`admin/banners/${route.params.id}`)
        .then((resp) => {
          const data = resp.data.data;
          if (resp?.data?.data?.category?.title) {
            cats.value[0].id = resp?.data?.data?.category?.id;
            cats.value[0].title = resp?.data?.data?.category?.title;
          }

          if (resp?.data?.data?.product?.title) {
            products.value[0].id = resp?.data?.data?.product?.id;
            products.value[0].title = resp?.data?.data?.product?.title;
          }

          if (resp?.data?.data?.category_page?.title) {
            catPages.value[0].id = resp?.data?.data?.category_page?.id;
            catPages.value[0].title = resp?.data?.data?.category_page?.title;
          }

          if (resp?.data?.data?.brand_page?.title) {
            brands.value[0].id = resp?.data?.data?.brand_page?.id;
            brands.value[0].title = resp?.data?.data?.brand_page?.title;
          }

          title.value = data?.title;
          pannel.value = data?.panel;
          imagePreview.value = data?.image;
          selectedLoc.value = data?.location;
          selectedLandingCat.value = data?.category_id;
          selectedLandingProduct.value = data?.product_id;
          pageType.value = data.page_type;
          if (data.page_id && pageType.value === "category") {
            selectedCatPage.value = data?.page_id;
          }

          if (data.page_id && pageType.value === "brand") {
            selectedBrandPage.value = data?.page_id;
          }

          if (selectedLandingProduct.value) {
            landingType.value = "product";
          }

          if (selectedLandingCat.value) {
            landingType.value = "cat";
          }
        })
        .catch((err) => {
          console.log(err);
        });
    };

    onMounted(() => {
      getBanner();
    });

    const submitForm = () => {
      if (!validateForm()) {
        toast.error("لطفا فیلد های لازم را وارد نمایید", {
          position: "top-right",
          autoClose: 1000,
        });
        return;
      }
      loading.value = true;
      const formData = new FormData();
      formData.append("title", title.value);

      if (pageType.value === "category") {
        formData.append("page_id", selectedCatPage.value);
      }

      if (pageType.value === "brand") {
        formData.append("page_id", selectedBrandPage.value);
      }

      if (landingType.value === "product") {
        formData.append("product_id", selectedLandingProduct.value);
      }

      if (landingType.value === "cat") {
        formData.append("category_id", selectedLandingCat.value);
      }

      if (selectedLoc.value === "A") {
        formData.append("type", pageType.value === 'blog_page' ? "banner" : "slider");
      }

      if (selectedLoc.value !== "A") {
        formData.append("type", "banner");
      }

      if (pannel.value === "wholesale") {
        formData.append("type", "slider");
        formData.append("location", "A");
      }

      formData.append("location", selectedLoc.value);

      formData.append("panel", pannel.value);

      if(pannel.value === 'web')
        formData.append("page_type", pageType.value);

      if (image.value) {
        formData.append("image", image.value);
      }

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

      ApiServiece.post(`admin/banners/${route.params.id}`, formData, {
        headers: {
          "content-type": "multipart",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      })
        .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 {
      cats,
      errors,
      title,
      products,
      selectedCatPage,
      submitForm,
      clearError,
      pageType,
      formattedProducts,
      landingType,
      selectedLandingCat,
      selectedLandingProduct,
      selectedLoc,
      pannel,
      handleImageUpload,
      image,
      imagePreview,
      loading,
      brands,
      handleSearch,
      formattedCategories,
      categorySelectorLoader,
      handleProductSearch,
      productSelectorLoader,
      formattedCatPages,
      handleCategoryPageSearch,
      categoryPageSelectorLoader,
      formattedBrands,
      brandSelectorLoader,
      handleBrandSearch,
      selectedBrandPage,
    };
  },
};
</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>
