<script>
import Layout from "@/layout/custom.vue";
import ApiServiece from "@/services/ApiService";
import VueSelect from "vue3-select-component";
import moment from "jalali-moment";
import { onMounted, ref, watch, computed } from "vue";
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import Swal from "sweetalert2";

export default {
  name: "BORDER",
  components: {
    Layout,
    VueSelect,
  },
  setup() {
    const brandSelectorLoader = ref(false);
    const categorySelectorLoader = ref(false);
    let searchTimeout = null;
    const selectedProductType = ref("");
    const categories = ref([]);
    const brands = ref();
    const selectedcategory = ref();
    const selectedBrand = ref();
    const searchPage = ref();
    const currentPage = ref(1);
    const totalPages = ref(1);
    const paginate = ref(20);
    const page = ref(1);
    function formatWithCommas(number) {
      return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    const filterLoading = ref(false);
    const searchQuery = ref("");
    const products = ref();

    const convertToJalali = (date) => {
      return moment(date, "YYYY-MM-DD HH:mm:ss")
        .locale("fa")
        .format("YYYY/MM/DD");
    };
    const handleSearchChange = () => {
      clearTimeout(searchTimeout);

      searchTimeout = setTimeout(() => {
        getProducts();
        page.value = 1;
      }, 500);
    };

    watch(searchQuery, () => {
      handleSearchChange();
      page.value = 1;
    });

    const getProducts = () => {
      filterLoading.value = true;
      let isSpecial;
      if (selectedProductType.value === "special") {
        isSpecial = 1;
      }
      if (selectedProductType.value === "chosen") {
        isSpecial = 2;
      }
      ApiServiece.get(
        `admin/products?title=${searchQuery.value || ""}&category_id=${
          selectedcategory.value || ""
        }&brand_id=${
          selectedBrand.value || ""
        }&discount_type=${isSpecial || ''}&paginate=${
          paginate.value || 10
        }&page=${page.value || 1}`
      )
        .then((resp) => {
          filterLoading.value = false;
          products.value = resp.data.data.data;
          console.log(resp.data.data);
          currentPage.value = resp.data.data.current_page;
          totalPages.value = resp.data.data.last_page;
        })
        .catch(() => {
          filterLoading.value = false;
        });
    };

    const visiblePages = computed(() => {
      const pages = [];
      if (totalPages.value <= 5) {
        for (let i = 1; i <= totalPages.value; i++) {
          pages.push(i);
        }
      } else {
        let start = currentPage.value - 2;
        let end = currentPage.value + 2;

        if (start < 1) {
          end += 1 - start;
          start = 1;
        }
        if (end > totalPages.value) {
          start -= end - totalPages.value;
          end = totalPages.value;
        }
        start = Math.max(start, 1);

        for (let i = start; i <= end; i++) {
          pages.push(i);
        }
      }
      return pages;
    });
    const deleteProduct = (id, title) => {
      Swal.fire({
        text: `می خواهید محصول ${title ?? ''} را حذف کنید؟`,
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: "بله!",
        cancelButtonText: "خیر",
      }).then((result) => {
        if (result.isConfirmed) {
          ApiServiece.delete(`admin/products/${id}`)
            .then(() => {
              toast.success("!محصول با موفقیت حذف شد", {
                position: "top-right",
                autoClose: 3000,
              });
            })
            .then(() => {
              getProducts();
            })
            .catch((err) => {
              console.log(err);
              toast.error("!مشکلی در حذف کردن محصول پیش آمد", {
                position: "top-right",
                autoClose: 3000,
              });
            });
        }
      });
    };

    const restoreProduct = (id, title) => {
      Swal.fire({
        text: `می خواهید محصول ${title ?? ''} را بازیابی کنید؟`,
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: "بله!",
        cancelButtonText: "خیر",
      }).then((result) => {
        if (result.isConfirmed) {
          ApiServiece.put(`admin/products/${id}/restore`)
            .then(() => {
              toast.success("!محصول با موفقیت بازیابی شد", {
                position: "top-right",
                autoClose: 3000,
              });
            })
            .then(() => {
              getProducts();
            })
            .catch((err) => {
              console.log(err);
              toast.error("!مشکلی در بازیابی محصول پیش آمد", {
                position: "top-right",
                autoClose: 3000,
              });
            });
        }
      });
    };

    function handlePageInput() {
      if (searchPage.value < 1) {
        searchPage.value = 1;
      } else if (searchPage.value > totalPages.value) {
        searchPage.value = totalPages.value;
      }

      if (searchPage.value >= 1 && searchPage.value <= totalPages.value) {
        page.value = searchPage.value;
      }
    }

    watch(page, () => {
      getProducts();
    });

    watch([selectedcategory, selectedBrand], () => {
      getProducts();
    });

    watch(selectedProductType, () => {
      getProducts();
    });

    const nextPage = () => {
      if (currentPage.value < totalPages.value) {
        page.value++;
        getProducts();
      }
    };

    const prevPage = () => {
      if (currentPage.value > 1) {
        page.value--;
        getProducts();
      }
    };

    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 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 formattedBrands = computed(() =>
      Array.isArray(brands.value)
        ? brands.value.map((brand) => ({
            value: brand?.id,
            label: brand?.translation?.title || '',
          }))
        : []
    );

    onMounted(() => {
      getProducts();
    });
    return {
      products,
      convertToJalali,
      deleteProduct,
      searchQuery,
      filterLoading,
      currentPage,
      totalPages,
      nextPage,
      prevPage,
      page,
      handlePageInput,
      searchPage,
      visiblePages,
      restoreProduct,
      formatWithCommas,
      handleSearch,
      formattedCategories,
      selectedcategory,
      selectedProductType,
      formattedBrands,
      handleBrandSearch,
      selectedBrand,
      categorySelectorLoader,
      brandSelectorLoader,
    };
  },
};
</script>

<template>
  <Layout>
    <BRow>
      <div class="col-md-12">
        <div class="card shadow-sm border-0 rounded">
          <div
            class="card-header d-flex justify-content-between align-items-center p-3"
            dir="rtl"
          >
            <div class="d-flex align-items-center">
              <input
                v-model="searchQuery"
                type="text"
                placeholder="جستجو..."
                class="form-control form-control-sm d-inline-block me-2"
                style="width: 250px; border-radius: 15px"
              />
              <select
                class="form-select form-select-sm"
                v-model="selectedProductType"
                style="width: 120px; border-radius: 15px"
              >
                <option value="" disabled selected>نوع محصول</option>
                <option value="">همه</option>
                <option value="chosen">برگزیده</option>
                <option value="special">ویژه</option>
              </select>

              <VueSelect
                style="
                  --vs-border-radius: 16px;
                  --vs-min-height: 18px;
                  margin-right: 7px;
                "
                :isLoading="categorySelectorLoader"
                v-model="selectedcategory"
                :options="formattedCategories"
                placeholder="دسته ای را انتخاب کنید"
                @search="handleSearch"
              />

              <VueSelect
                style="
                  --vs-border-radius: 16px;
                  --vs-min-height: 18px;
                  margin-right: 7px;
                "
                v-model="selectedBrand"
                :isLoading="brandSelectorLoader"
                :options="formattedBrands"
                placeholder="برندی را انتخاب کنید"
                @search="handleBrandSearch"
              />
            </div>
            <router-link
              to="/addProduct"
              class="btn btn-light text-primary btn-sm px-3"
            >
              افزودن محصول
            </router-link>
          </div>
          <div v-if="!filterLoading" class="card-body table-border-style p-0">
            <div class="table-responsive">
              <table class="table table-hover table-bordered m-0" dir="rtl">
                <thead class="table-light">
                  <tr>
                    <th>عکس</th>
                    <th>عنوان</th>
                    <th>دسته بندی</th>
                    <th>برند</th>
                    <th>تعداد فروش</th>
                    <th>قیمت</th>
                    <th>وزن</th>
                    <th>وضعیت</th>
                    <th>عملیات</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="product in products" :key="product.id">
                    <td>
                      <img
                        :src="product?.image"
                        alt="Product Image"
                        class="Product-Image"
                      />
                    </td>
                    <td v-if="!product.image">ندارد</td>

                    <td>{{ product?.translation?.title }}</td>


                    <td>{{ product?.category?.translation?.title }}</td>

                    <td>{{ product?.brand?.translation?.title }}</td>

                    <td>{{ product?.sold_count }}</td>

                    <td>
                      {{ formatWithCommas(product.price) }}
                    </td>

                    <td>
                      {{ product?.weight }}
                    </td>

                    <td v-if="!product.deleted_at">
                      <span class="badge bg-success text-white">فعال</span>
                    </td>
                    <td v-if="product.deleted_at">
                      <span class="badge bg-danger text-white">حذف شده</span>
                    </td>

                    <td>
                      <router-link
                        :to="`/editProduct/${product?.id}`"
                        class="btn btn-sm btn-outline-warning me-1"
                      >
                        ویرایش
                      </router-link>
                      <button
                        v-if="!product.deleted_at"
                        @click="deleteProduct(product?.id, product?.translation?.title)"
                        class="btn btn-sm btn-outline-danger me-1"
                      >
                        حذف
                      </button>

                      <button
                        v-else
                        @click="restoreProduct(product?.id, product?.translation?.title)"
                        class="btn btn-sm btn-outline-success"
                      >
                        بازیابی
                      </button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
          <div
            v-else
            class="filter-loader card table-card user-profile-list"
          ></div>
        </div>
      </div>
    </BRow>
    <BRow>
      <BCol sm="12">
        <div class="d-flex justify-content-center">
          <nav aria-label="Page navigation">
            <ul class="pagination">
              <!-- Previous page -->
              <li class="page-item" :class="{ disabled: currentPage === 1 }">
                <span class="page-link" @click="prevPage">قبلی</span>
              </li>

              <!-- First page and leading dots -->
              <li
                v-if="visiblePages[0] > 1"
                class="page-item"
                @click="page = 1"
              >
                <a class="page-link" href="javascript:void(0)">1</a>
              </li>
              <li v-if="visiblePages[0] > 2" class="page-item disabled">
                <span class="page-link">...</span>
              </li>

              <!-- Visible pages -->
              <li
                v-for="n in visiblePages"
                :key="n"
                class="page-item"
                :class="{ active: currentPage === n }"
              >
                <a
                  class="page-link"
                  href="javascript:void(0)"
                  @click="page = n"
                >
                  {{ n }}
                </a>
              </li>

              <!-- Trailing dots and last page -->
              <li
                v-if="visiblePages[visiblePages.length - 1] < totalPages - 1"
                class="page-item disabled"
              >
                <span class="page-link">...</span>
              </li>
              <li
                v-if="visiblePages[visiblePages.length - 1] < totalPages"
                class="page-item"
                @click="page = totalPages"
              >
                <a class="page-link" href="javascript:void(0)">
                  {{ totalPages }}
                </a>
              </li>

              <!-- Next page -->
              <li
                class="page-item"
                :class="{ disabled: currentPage === totalPages }"
              >
                <span class="page-link" @click="nextPage">بعدی</span>
              </li>
            </ul>
          </nav>
        </div>
      </BCol>
      <BCol sm="4">
        <div class="ms-0 search-number">
          <input
            v-model="searchPage"
            type="text"
            class="form-control"
            placeholder="برو به صفحه"
            :max="totalPages"
            min="1"
            @input="handlePageInput"
          />
        </div>
      </BCol>
    </BRow>
  </Layout>
</template>

<style scoped>
.card {
  transition: transform 0.3s ease;
}
.card:hover {
  transform: translateY(-3px);
}

.filter-loader {
  border: 4px solid rgba(0, 123, 255, 0.3);
  border-top: 4px solid #007bff;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin: 20px auto;
}
.Product-Image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 8px;
  border: 1px solid #ddd;
}
.subject-box {
  padding: 8px 14px;
  background: linear-gradient(135deg, #fff3e0, #ffe0b2);
  color: #ef6c00;
  font-weight: 600;
  border-radius: 10px;
  box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.1);
  display: inline-flex;
  align-items: center;
  gap: 8px;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.subject-box i {
  color: #ef6c00;
  font-size: 1rem;
}

.subject-box:hover {
  transform: translateY(-2px);
  box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.15);
}
.search-number {
  display: flex;
  align-items: center;
}

.search-number input {
  width: 150px;
  padding: 0.5rem;
  font-size: 1rem;
  border-radius: 0.375rem;
  margin-bottom: 7px;
  border: 1px solid #ced4da;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
}

.search-number input:focus {
  border-color: #007bff;
  box-shadow: 0 0 0 0.2rem rgba(38, 143, 255, 0.25);
}

.search-number input::placeholder {
  color: #6c757d;
}

.search-number input:disabled {
  background-color: #f8f9fa;
  cursor: not-allowed;
}
.pagination {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.page-link {
  cursor: pointer;
  user-select: none;
}
.table {
  border-radius: 8px;
  overflow: hidden;
  font-size: 0.9rem;
  border-collapse: separate;
  border-spacing: 0;
}

.table th,
.table td {
  padding: 12px 16px;
  text-align: center;
  vertical-align: middle;
}

.table th {
  font-weight: bold;
}

.Product-Image {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 5px;
}

.status-icon {
  margin-left: 5px;
}

.status-icon.available {
  color: #28a745;
}

.status-icon.unavailable {
  color: #dc3545;
}

.btn-outline-warning {
  color: #ffc107;
  border-color: #ffc107;
  transition: background-color 0.3s, color 0.3s;
}

.btn-outline-warning:hover {
  background-color: #ffc107;
  color: #fff;
}

.btn-outline-danger {
  color: #dc3545;
  border-color: #dc3545;
  transition: background-color 0.3s, color 0.3s;
}

.btn-outline-danger:hover {
  background-color: #dc3545;
  color: #fff;
}

td,
table[dir="rtl"] td,
table[dir="rtl"] th {
  text-align: center;
}

td:last-child {
  justify-content: center;

  align-items: center;
}
</style>
