<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 editUser from "@/components/modals/editUser.vue";
import addUser from "@/components/modals/addUser.vue";
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
export default {
  name: "SAMPLE-PAGE",
  components: {
    Layout,
    editUser,
    addUser,
  },
  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 users = ref([]);
    const userName = ref();
    const userMobile = ref();
    const userId = ref();
    const userRole = ref();
    const userCountryCode = ref();
    const selectedRole = ref("");
    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 getUsers = () => {
      filterLoading.value = true;
      ApiServiece.get(
        `admin/users?name=${searchQuery.value || ""}&paginate=${
          paginate.value || 10
        }&page=${page.value || 1}&role=${
          selectedRole.value || ""
        }&trashed=${selectedStatus.value || ""}`
      )
        .then((resp) => {
          users.value = resp.data.data.data;
          currentPage.value = resp.data.data.current_page;
          totalPages.value = resp.data.data.last_page;
          filterLoading.value = false;
        })
        .catch(() => {
          filterLoading.value = false;
        });
    };

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

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

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

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

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

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

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

    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 = (id, name, mobile, role, config_id) => {
      userName.value = name;
      userMobile.value = mobile;
      userId.value = id;
      userRole.value = role;
      userCountryCode.value = config_id;
    };

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

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

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

    return {
      users,
      convertToJalali,
      searchQuery,
      modalData,
      userName,
      userMobile,
      userId,
      handleUserUpdated,
      blockUser,
      unBlockUser,
      userRole,
      handlePageInput,
      nextPage,
      paginate,
      totalPages,
      currentPage,
      prevPage,
      visiblePages,
      page,
      searchPage,
      selectedRole,
      selectedStatus,
      filterLoading,
      userProfile,
      userCountryCode,
    };
  },
};
</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"
                />

                <!-- User Role Selector -->
                <select
                  class="form-select form-select-sm"
                  v-model="selectedRole"
                  style="width: 120px; border-radius: 15px"
                >
                  <option value="" disabled selected>نقش کاربر</option>
                  <option value="">همه</option>
                  <option value="admin">فقط مدیران</option>
                  <option value="operator">فقط اپراتورها</option>
                </select>

                <select
                  class="form-select form-select-sm"
                  v-model="selectedStatus"
                  style="width: 120px; border-radius: 15px"
                >
                  <option value="" disabled selected>وضعیت</option>
                  <option value="">همه</option>
                  <option value="0">فعال</option>
                  <option value="1">بلاک</option>
                </select>

                <!-- User Status Selector -->
                <!-- <select
                  v-model="selectedStatus"
                  class="form-select filter-input"
                >
                  <option value="" disabled selected>انتخاب وضعیت کاربر</option>
                  <option value="active">فعال</option>
                  <option value="blocked">بلاک</option>
                </select> -->

                <!-- Add User Button -->
              </div>
              <button
                v-if="userProfile?.role === 'admin'"
                data-bs-toggle="modal"
                data-bs-target="#addUser"
                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="user in users" :key="user.id">
                    <td>
                      <div class="d-inline-block align-middle">
                        <img
                          src="@/assets/images/user/avatar-1.jpg"
                          alt="user image"
                          class="img-radius align-top m-r-15"
                          style="width: 40px"
                        />
                        <div class="d-inline-block users-names">
                          <h6 v-if="user.name" class="m-b-0">
                            {{ user?.name }}
                          </h6>
                          <h6 v-else class="m-b-0">بی نام</h6>
                        </div>
                      </div>
                    </td>

                    <td>{{ user?.mobile }}</td>
                    <td v-if="user.role === 'admin'">مدیر</td>
                    <td v-if="user.role === 'client'">مشتری</td>
                    <td v-if="user.role === 'operator'">اپراتور</td>
                    <td>{{ convertToJalali(user.created_at) }}</td>
                    <td>
                      <span
                        v-if="!user.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(
                                  user.id,
                                  user.name,
                                  user.mobile,
                                  user.role,
                                  user?.country_config_id
                                )
                              "
                              data-bs-toggle="modal"
                              data-bs-target="#editUser"
                              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
                              v-if="!user.deleted_at"
                              @click="blockUser(user.id)"
                              href="#"
                              class="avtar avtar-s btn bg-white btn-link-danger"
                            >
                              <i class="ti ti-lock f-18"></i>
                            </a>
                            <a
                              @click="unBlockUser(user.id)"
                              v-else
                              href="#"
                              class="avtar avtar-s btn bg-white btn-link-success"
                            >
                              <i class="fa fa-unlock-alt 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>
      <editUser
        @user-updated="handleUserUpdated"
        :name="userName"
        :mobile="userMobile"
        :id="userId"
        :role="userRole"
        :countryCode="userCountryCode"
      />
      <addUser @user-updated="handleUserUpdated" />
    </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>
.users-names {
  margin-top: 7px;
}

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

.search-input {
  width: 250px;
  padding: 10px 16px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 8px;
  margin-right: 16px;
  transition: all 0.3s ease;
}

.filter-input {
  padding: 10px 16px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 8px;
  margin-right: 16px;
  transition: all 0.3s ease;
}

.search-input:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 8px rgba(0, 123, 255, 0.3);
}

.btn-dropdown {
  padding: 10px 16px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 8px;
  background-color: white;
  transition: all 0.3s ease;
}

.btn-dropdown:hover {
  background-color: #f1f1f1;
  border-color: #007bff;
}

.dropdown-menu {
  border-radius: 8px;
}

.dropdown-item {
  padding: 12px 16px;
  font-size: 14px;
  color: #333;
  transition: background-color 0.3s ease;
}

.dropdown {
  margin-right: 5px;
}

.dropdown-item:hover {
  background-color: #f1f1f1;
}

.btn-add-user {
  width: 100px;
  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>
