<script>
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 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 convertToJalali = (date) => {
      return moment(date, "YYYY-MM-DD HH:mm:ss")
        .locale("fa")
        .format("YYYY/MM/DD");
    };

    const getUsers = () => {
      ApiServiece.get(
        `admin/users?name=${searchQuery.value || ""}&paginate=${
          paginate.value || 10
        }&page=${page.value || 1}`
      ).then((resp) => {
        console.log(resp.data.data);
        users.value = resp.data.data.data;
        currentPage.value = resp.data.data.current_page;
        totalPages.value = resp.data.data.last_page;
      });
    };

    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) start = 1;
        if (end > totalPages.value) end = totalPages.value;

        for (let i = start; i <= end; i++) {
          pages.push(i);
        }
      }
      return pages;
    });

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

    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) => {
      userName.value = name;
      userMobile.value = mobile;
      userId.value = id;
      userRole.value = role;
    };
    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,
    };
  },
};
</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">
                <input
                  type="text"
                  class="form-control search-input"
                  placeholder="جستجو بر اساس نام کاربر"
                  id="search-users"
                  v-model="searchQuery"
                />

                <!-- <div class="dropdown">
                  <button
                    class="btn btn-dropdown"
                    type="button"
                    id="filtersDropdown"
                    data-bs-toggle="dropdown"
                    aria-expanded="false"
                  >
                    فیلترها
                  </button>
                  <ul class="dropdown-menu" aria-labelledby="filtersDropdown">
                    <li><a class="dropdown-item" href="#">همه کاربران</a></li>
                    <li><a class="dropdown-item" href="#">فقط مدیران</a></li>
                    <li><a class="dropdown-item" href="#">فقط مشتریان</a></li>
                    <li><a class="dropdown-item" href="#">فعال</a></li>
                    <li><a class="dropdown-item" href="#">بلاک</a></li>
                  </ul>
                </div> -->
                <button
                  data-bs-toggle="modal"
                  data-bs-target="#addUser"
                  class="btn btn-add-user me-3"
                >
                  افزودن کاربر
                </button>
              </div>
            </div>

            <div 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
                                )
                              "
                              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>
        </div>
      </div>
      <editUser
        @user-updated="handleUserUpdated"
        :name="userName"
        :mobile="userMobile"
        :id="userId"
        :role="userRole"
      />
      <addUser @user-updated="handleUserUpdated" />
    </BRow>
    <BRow>
      <BCol sm="12">
        <div class="d-flex justify-content-center">
          <nav aria-label="Page navigation">
            <ul class="pagination">
              <li class="page-item" :class="{ disabled: currentPage === 1 }">
                <span class="page-link" @click="prevPage">قبلی</span>
              </li>

              <li v-if="currentPage > 2" class="page-item" @click="page = 1">
                <a class="page-link" href="javascript:void(0)">1</a>
              </li>
              <li v-if="currentPage > 3" class="page-item" disabled>
                <span class="page-link">...</span>
              </li>

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

              <li
                v-if="currentPage < totalPages - 2"
                class="page-item"
                disabled
              >
                <span class="page-link">...</span>
              </li>
              <li
                v-if="currentPage < totalPages - 1"
                class="page-item"
                @click="page = totalPages"
              >
                <a class="page-link" href="javascript:void(0)">{{
                  totalPages
                }}</a>
              </li>

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

.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 {
  display: flex;
  align-items: center;
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  font-size: 14px;
  border-radius: 8px;
  border: none;
  transition: all 0.3s ease;
}

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

.btn-add-user:hover {
  background-color: #0056b3;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.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;
}
</style>
