<script>
import { debounce } from "lodash";
import Layout from "@/layout/custom.vue";
import { onMounted, ref, watch, computed } from "vue";
import Swal from "sweetalert2";
import ApiServiece from "@/services/ApiService";
import moment from "jalali-moment";
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import CountriesModal from "@/components/modals/countries/CountriesModal.vue";
export default {
  name: "SAMPLE-PAGE",
  components: {
    CountriesModal,
    Layout,
  },
  setup() {
    const selectedStatus = ref("");
    const filterLoading = ref(false);
    const searchPage = ref();
    const currentPage = ref(1);
    const totalPages = ref(1);
    const paginate = ref(20);
    const page = ref(1);
    const searchQuery = ref("");
    const countries = ref([]);
    const userName = ref();
    const userMobile = ref();
    const userId = ref();
    const userRole = ref();
    const selectedRole = ref("");
    const countryModalRef = ref(null);
    const userProfile = JSON.parse(localStorage.getItem('user_profile'));

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

    const getCountries = async () => {
      try {
        filterLoading.value = true;
        const { data: { success, data } } = await ApiServiece.get('admin/country-configs', {
          params: {
            paginate: paginate.value,
            page: currentPage.value,
            title: searchQuery.value,
          }
        })

        if(success) {
          countries.value = data?.data
          currentPage.value = data?.current_page;
          totalPages.value = data?.last_page;
        }
      } catch (e) {
        toast.error(e?.response?.data?.message);
      } finally {
        filterLoading.value = false;
      }
    };

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

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

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

    watch(selectedRole, () => {
      getCountries();
    });

    watch(selectedStatus, () => {
      getCountries();
    });

    watch(searchQuery, (newQuery) => {
      debouncedSearch(newQuery);
    });

    const debouncedSearch = debounce(() => {
      getCountries();
    }, 1000);

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

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

    const modalData = (item) => {
      Object.assign(countryModalRef.value.form, item)
    };

    const handleUserUpdated = () => {
      getCountries();
    };

    const deleteUser = (id) => {
      Swal.fire({
        text: "آیا میخواهید این کاربر را حذف کنید؟",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "بله",
        cancelButtonText: "خیر",
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
      }).then((result) => {
        if (result.isConfirmed) {
          ApiServiece.delete(`admin/country-configs/${id}`)
              .then((res) => {
                toast.success(res?.data?.message , {
                  position: "top-right",
                  autoClose: 1000,
                });
              })
              .then(() => {
                getCountries();
              })
              .catch((err) => {
                toast.error(err?.response?.data?.message, {
                  position: "top-right",
                  autoClose: 1000,
                });
              });
        }
      });
    };

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

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

    return {
      countries,
      convertToJalali,
      searchQuery,
      modalData,
      userName,
      userMobile,
      userId,
      handleUserUpdated,
      deleteUser,
      unBlockUser,
      userRole,
      handlePageInput,
      nextPage,
      paginate,
      totalPages,
      currentPage,
      prevPage,
      visiblePages,
      page,
      searchPage,
      selectedRole,
      selectedStatus,
      filterLoading,
      userProfile,
      getCountries,
      countryModalRef
    };
  },
};
</script>

<template>
  <Layout>
    <BRow>
      <div class="col-sm-12">
        <div class="card table-card user-profile-list">
          <div class="card-body">
            <div class="filter-container">
              <div class="search-filters d-flex align-items-center gap-3">
                <!-- Search Input -->
                <input
                    v-model="searchQuery"
                    type="text"
                    placeholder="جستجو..."
                    class="form-control form-control-sm d-inline-block me-2"
                    style="width: 250px; border-radius: 15px"
                />
              </div>
              <button
                  v-if="userProfile?.role === 'admin'"
                  data-bs-toggle="modal"
                  data-bs-target="#countriesModal"
                  class="btn btn-add-user btn btn-light text-primary btn-sm px-3"
              >
                افزودن کشور
              </button>
            </div>

            <div v-if="!filterLoading" class="table-responsive">
              <table class="table table-hover" id="pc-dt-simple">
                <thead>
                <tr>
                  <th>پیش شماره</th>
                  <th>کشور</th>
                  <th>حداقل وزن حمل ونقل</th>
                  <th>هزینه هر کیلوگرم</th>
                  <th>وضعیت</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="country in countries" :key="country.id">
                  <td>
                    {{ country?.country_code }}
                  </td>
                  <td>
                    {{ country?.title }}
                  </td>
                  <td>
                    {{ country?.minimum_shipping_weight }}
                  </td>
                  <td>
                    {{ country?.per_kilograms_cost }}
                  </td>
                  <td>
                    <span v-if="!country?.deleted_at" class="badge bg-light-success">فعال</span>
                    <span v-else class="badge bg-light-danger">بلاک</span>
                    <div class="overlay-edit">
                      <ul class="list-inline mb-0">
                        <li class="list-inline-item m-0">
                          <a
                              @click="modalData(country)"
                              data-bs-toggle="modal"
                              data-bs-target="#countriesModal"
                              href="#"
                              class="avtar avtar-s btn btn-primary"
                          >
                            <i class="ti ti-pencil f-18"></i>
                          </a>
                        </li>
                        <li class="list-inline-item m-0">
                          <a
                              @click="deleteUser(country?.id)"
                              href="#"
                              class="avtar avtar-s btn bg-white btn-link-danger"
                          >
                            <i class="ti ti-trash f-18"></i>
                          </a>
                        </li>
                      </ul>
                    </div>
                  </td>
                </tr>
                </tbody>
              </table>
            </div>
            <div
                v-else
                class="filter-loader card table-card user-profile-list"
            ></div>
          </div>
        </div>
      </div>
      <CountriesModal ref="countryModalRef" @country-updated="getCountries" />
    </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>
.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px;
  background-color: #fafafa;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-filters {
  display: flex;
  align-items: center;
}

.btn-add-user {
  align-items: center;
  padding: 10px 20px;
  color: white;
  font-size: 14px;
  border-radius: 8px;
  border: none;
  transition: all 0.3s ease;
}

.btn-add-user i {
  margin-right: 8px;
}

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