<script>
import Layout from "@/layout/custom.vue";
import ApiServiece from "@/services/ApiService";
import { onMounted, ref, watch, computed } from "vue";
import DatePicker from "vue3-persian-datetime-picker";
import VueSelect from "vue3-select-component";
import showDescription from "@/components/modals/commonModals/showDescription.vue";
import moment from "jalali-moment";
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import Swal from "sweetalert2";
export default {
  name: "PRODUCT-LIST",
  components: {
    Layout,
    VueSelect,
    DatePicker,
    showDescription,
  },
  setup() {
    const productDescription = ref("");
    const selectorLoader = ref(false);
    const isLoading = ref(false);
    const date = ref([]);
    const brands = ref([]);
    const searchPage = ref();
    const currentPage = ref(1);
    const totalPages = ref(1);
    const paginate = ref(20);
    const page = ref(1);
    const filterLoading = ref(false);
    const selectedBrand = ref();
    const orders = ref([]);
    const changeStatus = (id, status) => {
      Swal.fire({
        text: `آیا می خواهید وضعیت سبد خرید را به ${getStatusLabel(
          status
        )} تغییر دهید؟ `,
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: "بله!",
        cancelButtonText: "خیر",
      }).then((result) => {
        if (result.isConfirmed) {
          const formData = new FormData();
          formData.append("status", status);
          ApiServiece.put(`admin/orders/order-items/${id}`, formData)
            .then(() => {
              toast.success("تغییر وضعیت سبد خرید با موفقیت انجام شد", {
                position: "top-right",
                autoClose: 3000,
              });
            })
            .then(() => {
              getAllOrders();
            })
            .catch((err) => {
              console.log(err);
              toast.error("!مشکلی در تغییر وضعیت سبد خرید پیش آمد", {
                position: "top-right",
                autoClose: 3000,
              });
            });
        }
      });
    };
    const descriptionModal = (desc) => {
      productDescription.value = desc;
    };
    const getAllOrders = () => {
      if (date.value[0]) {
        date.value[0] = moment(date.value[0], "YYYY-MM-DD HH:mm:ss").format(
          "YYYY/MM/DD HH:mm:ss"
        );
      }

      if (date.value[1]) {
        date.value[1] = moment(date.value[1], "YYYY-MM-DD HH:mm:ss").format(
          "YYYY/MM/DD HH:mm:ss"
        );
      }

      filterLoading.value = true;
      ApiServiece.get(
        `admin/orders/order-items/approved?brand_id=${
          selectedBrand.value || ""
        }&start_date=${date.value[0] || ""}&end_date=${
          date.value[1] || ""
        }&paginate=${paginate.value || 10}&page=${page.value || 1}`
      )
        .then((resp) => {
          filterLoading.value = false;
          orders.value = resp.data.data.data;

          currentPage.value = resp.data.data.current_page;
          totalPages.value = resp.data.data.last_page;
        })
        .catch(() => {
          filterLoading.value = false;
        });
    };

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

    const getStatusLabel = (status) => {
      const statusLabels = {
        waiting: "در انتظار",
        paid: "پرداخت‌شده",
        un_paid: "پرداخت‌نشده",
        approved: "تأیید‌شده",
        processing: "در حال پردازش",
        shipping: "در حال ارسال",
        delivered: "تحویل‌شده",
        canceled: "لغو‌شده",
        in_cart: "در سبد خرید",
        done: "کامل شده",
      };
      return statusLabels[status] || "نامشخص";
    };

    const getStatusClass = (status) => {
      const statusClasses = {
        waiting: "badge-waiting",
        paid: "badge-paid",
        un_paid: "badge-un_paid",
        approved: "badge-approved",
        processing: "badge-processing",
        shipping: "badge-shipping",
        delivered: "badge-delivered",
        canceled: "badge-canceled",
        in_cart: "badge-in-cart",
        done: "badge-in-done",
      };
      return statusClasses[status] || "badge-secondary";
    };

    const getFile = () => {
      isLoading.value = true;
      ApiServiece.post(
        "admin/orders/order-items/approved/export",
        {},
        { responseType: "blob" }
      )
        .then((resp) => {
          const excelBlob = resp.data;

          const url = window.URL.createObjectURL(excelBlob);

          const link = document.createElement("a");

          link.href = url;
          link.setAttribute("download", "order-items-export.xlsx");
          document.body.appendChild(link);

          link.click();

          window.URL.revokeObjectURL(url);

          document.body.removeChild(link);

          isLoading.value = false;
        })
        .catch((err) => {
          console.log(err);
          isLoading.value = false;
        });
    };

    watch(selectedBrand, () => {
      getAllOrders();
      page.value = 1;
    });

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

    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(selectedBrand, () => {
      getAllOrders();
    });

    watch(date, () => {
      getAllOrders();
    });

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

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

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

    function formatWithCommas(number) {
      return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

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

    const formattedBrands = computed(() =>
      Array.isArray(brands.value)
        ? brands.value.map((brand) => ({
            value: brand.id,
            label: brand.title,
          }))
        : []
    );

    onMounted(() => {
      getAllOrders();
    });
    return {
      orders,
      visiblePages,
      nextPage,
      prevPage,
      handlePageInput,
      currentPage,
      totalPages,
      page,
      getFile,
      convertToJalali,
      searchPage,
      brands,
      formattedBrands,
      selectedBrand,
      date,
      isLoading,
      formatWithCommas,
      handleBrandSearch,
      filterLoading,
      selectorLoader,
      productDescription,
      descriptionModal,
      getStatusLabel,
      getStatusClass,
      changeStatus,
    };
  },
};
</script>

<template>
  <Layout>
    <BRow>
      <BCol class="col-sm-12">
        <BCard no-body class="table-card">
          <BCardBody>
            <div
              class="card-header d-flex justify-content-between align-items-center p-3"
              dir="rtl"
            >
              <div class="d-flex align-items-center gap-3">
                <!-- VueSelect for Brand Selection -->
                <VueSelect
                  style="--vs-border-radius: 8px; min-width: 180px"
                  v-model="selectedBrand"
                  :options="formattedBrands"
                  :isLoading="selectorLoader"
                  placeholder="برندی را انتخاب کنید"
                  @search="handleBrandSearch"
                />

                <!-- Date Picker with Proper Width -->
                <DatePicker
                  :format="'jYYYY/jMM/jDD HH:mm:ss'"
                  type="datetime"
                  :range="true"
                  v-model="date"
                  class="custom-datepicker"
                />
              </div>

              <!-- Export Button with Better Spacing -->
              <button
                @click="getFile"
                type="button"
                class="btn btn-light text-primary btn-sm px-4"
                :disabled="isLoading"
              >
                <span
                  v-if="isLoading"
                  class="spinner-border spinner-border-sm"
                  role="status"
                  aria-hidden="true"
                ></span>
                <span v-else>گرفتن خروجی</span>
              </button>
            </div>

            <div class="table-responsive" v-if="!filterLoading">
              <table
                class="table table-hover align-middle text-center"
                id="pc-dt-simple"
              >
                <thead class="table-light">
                  <tr>
                    <th class="text-start">جزییات محصول</th>
                    <th>رنگ محصول</th>
                    <th>وضعیت</th>
                    <th>تاریخ ایجاد</th>
                    <th>قیمت عمده</th>
                    <th>قیمت تک</th>
                    <th>تعداد سفارش</th>
                    <th>تعداد ارسال شده</th>
                    <th>عملیات</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="order in orders" :key="order?.id">
                    <!-- Product Details -->
                    <td class="text-start" style="max-width: 200px; white-space: normal !important;">
                      <div class="d-flex align-items-center gap-3">
                        <img
                          :src="order?.product?.image"
                          alt="product"
                          class="rounded"
                          style="width: 50px; height: 50px; object-fit: cover"
                        />
                        <div>
                          <div class="fw-semibold">
                            {{ order?.product?.title }}
                          </div>
                          <div class="text-muted small">
                            {{ order.product.description.slice(0, 25) }}
                            <span v-if="order.product.description.length > 25"
                              >...</span
                            >
                          </div>
                        </div>
                      </div>
                    </td>

                    <!-- Product color -->
                    <td>
                      {{ order?.attribute_value_product?.attribute_value?.title }}
                    </td>

                    <!-- Status -->
                    <td>
                      <span class="badge" :class="getStatusClass(order.status)">
                        {{ getStatusLabel(order.status) }}
                      </span>
                    </td>

                    <!-- Created Date -->
                    <td>{{ convertToJalali(order.created_at) }}</td>

                    <!-- Wholesale Price -->
                    <td>
                      <span v-if="order?.product?.wholesale_price">
                        {{ formatWithCommas(order?.product?.wholesale_price) }}
                        تومان
                      </span>
                      <i
                        v-else
                        class="ph-duotone ph-x-circle text-danger fs-5"
                        title="قیمت نامشخص"
                      ></i>
                    </td>

                    <!-- Retail Price -->
                    <td>
                      <span v-if="order?.product?.retail_price">
                        {{ formatWithCommas(order?.product?.retail_price) }}
                      </span>
                      <i
                        v-else
                        class="ph-duotone ph-x-circle text-danger fs-5"
                        title="قیمت نامشخص"
                      ></i>
                    </td>

                    <!-- Order Count -->
                    <td>{{ order.count }}</td>

                    <!-- Sent Count -->
                    <td>{{ order.send_count }}</td>

                    <!-- Operations -->
                    <td>
                      <router-link
                        :to="`/singleOrder/${order?.order_id}`"
                        class="btn btn-sm btn-outline-primary me-1"
                      >
                        مشاهده و ویرایش
                      </router-link>
                      <button
                        class="btn btn-sm btn-outline-warning dropdown-toggle me-1"
                        type="button"
                        id="dropdownMenuButton"
                        data-bs-toggle="dropdown"
                        aria-expanded="false"
                      >
                        ویرایش وضعیت
                      </button>
                      <ul
                        class="dropdown-menu"
                        aria-labelledby="dropdownMenuButton"
                        style="cursor: pointer"
                      >
                        <li>
                          <a
                            class="dropdown-item d-flex justify-content-center align-items-center"
                            @click="changeStatus(order?.id, 'done')"
                          >
                            <span class="badge badge-in-done">کامل شده</span>
                          </a>
                        </li>
                        <li>
                          <a
                            class="dropdown-item d-flex justify-content-center align-items-center"
                            @click="changeStatus(order?.id, 'processing')"
                          >
                            <span class="badge badge-processing"
                              >در حال پردازش</span
                            >
                          </a>
                        </li>
                      </ul>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div
              v-else
                   class="filter-loader card table-card user-profile-list"
            ></div>
          </BCardBody>
        </BCard>
      </BCol>
    </BRow>
    <showDescription :desc="productDescription" />
    <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>
.product-img {
  max-width: 48px;
  min-width: 48px;
  max-height: 45px;
  min-height: 45px;
  object-fit: cover;
}
.brand-img {
  max-width: 43px;
  min-width: 43px;
  max-height: 40px;
  min-height: 40px;
  object-fit: cover;
}
.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-item {
  flex: 0 0 auto;
}

.page-link {
  cursor: pointer;
  user-select: none;
}
.custom-datepicker {
  min-width: 340px;
}
.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);
}
.badge {
  display: inline-block;
  padding: 5px 10px;
  border-radius: 12px;
  font-size: 0.85rem;
  font-weight: 500;
  text-transform: capitalize;
  color: white;
}

.badge-waiting {
  background-color: #ffc107;
}
.badge-paid {
  background-color: #28a745;
}
.badge-un_paid {
  background-color: #dc3545;
}
.badge-approved {
  background-color: #17a2b8;
}
.badge-processing {
  background-color: #007bff;
}
.badge-shipping {
  background-color: #6f42c1;
}
.badge-delivered {
  background-color: #20c997;
}
.badge-canceled {
  background-color: #6c757d;
}
.badge-in-cart {
  background-color: #0620c6; /* You can choose any color you prefer */
}
.badge-in-done {
  background-color: #a2ca2c; /* You can choose any color you prefer */
}
.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;
}

</style>
