<template>
  <div class="users-page">
    <BoxedIconTitleBlock
      class="users-page__heading"
      title="مدیریت کاربران"
      desc="در این قسمت می‌توانید کاربران خود را مدیریت کنید"
    >
      <template #icon>
        <SvgIcon name="users-three" :size="24" color="var(--color-primary)" />
      </template>
    </BoxedIconTitleBlock>

    <UsersFilters v-model="filters" @apply="onFilterApply" @reset="onFilterReset" />

    <div class="users-page__list-header">
      <SimpleTitleIconBlock title="لیست همه کاربران" class="users-page__list-title">
        <template #header-icon>
          <SvgIcon name="users" :size="16" color="#bcbcbc" />
        </template>
      </SimpleTitleIconBlock>
      <BaseButton text="افزودن کاربر جدید" custom-class="users-page__add-btn" @click="onAdd">
        <template #appendIcon>
          <SvgIcon name="arrow-left" :size="18" color="#fff" />
        </template>
      </BaseButton>
    </div>

    <SkeletonLoaderBlock v-if="isLoading" :rows="6" :cols-per-row="1" />
    <UsersTable
      v-else-if="users.length > 0"
      :users="users"
      @edit="onEdit"
      @delete="onAskDelete"
      @block="onAskBlock"
      @unblock="onAskUnblock"
      @show-details="onShowDetails"
    />
    <NoItems v-else title="متاسفیم" desc="کاربری برای نمایش وجود ندارد." />

    <PaginationBlock :pagination="paginationMeta" @update:page="setPage" />

    <UserDetailsModal v-if="isModal('UserDetailsModal')" />
  </div>
</template>

<script setup>
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import useModal from '@/composables/useModal'
import { useQueryClient } from '@tanstack/vue-query'
import BaseButton from '@/components/BaseButton.vue'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import NoItems from '@/components/blocks/NoItems.vue'
import { usePagination } from '@/composables/usePagination'
import PaginationBlock from '@/components/blocks/PaginationBlock.vue'
import UsersTable from '@/features/admin/users/components/UsersTable.vue'
import BoxedIconTitleBlock from '@/components/blocks/BoxedIconTitleBlock.vue'
import SkeletonLoaderBlock from '@/components/blocks/SkeletonLoaderBlock.vue'
import UsersFilters from '@/features/admin/users/components/UsersFilters.vue'
import SimpleTitleIconBlock from '@/components/blocks/SimpleTitleIconBlock.vue'
import UserDetailsModal from '@/features/admin/users/components/modals/UserDetailsModal.vue'
import {
  adminUsersKeys,
  useAdminUsersListQuery,
  useChangeAdminUserStatusMutation,
  useDeleteAdminUserMutation,
} from '@/services/query/admin-users'

const router = useRouter()
const queryClient = useQueryClient()
const { openModal, isModal } = useModal()

const filters = ref({ name: '', nationalCode: '', phone: '', role: '' })
const { pagination, setPage, reset: resetPagination } = usePagination({ page: 1, perPage: 10 })

const { data, isLoading } = useAdminUsersListQuery(filters, pagination, {
  keepPreviousData: true,
})

const users = computed(() => data.value?.data ?? [])
const paginationMeta = computed(() => ({
  page: pagination.value.page,
  perPage: pagination.value.perPage,
  ...data.value?.meta,
}))

const onFilterApply = () => resetPagination()
const onFilterReset = () => resetPagination()

const onAdd = () => {
  router.push({ name: 'admin-add-user' }).catch(() => {})
}

const onEdit = (user) => {
  router.push({ name: 'admin-edit-user', params: { id: user.id } }).catch(() => {})
}

const onShowDetails = (user) => openModal('UserDetailsModal', { id: user.id })

const invalidateUsers = () => queryClient.invalidateQueries({ queryKey: adminUsersKeys.all })

const userName = (user) =>
  user.name || `${user.firstName || ''} ${user.lastName || ''}`.trim() || user.phone

const deleteMutation = useDeleteAdminUserMutation()

const onAskDelete = (user) => {
  openModal('ConfirmModal', {
    title: 'حذف کاربر',
    message: `آیا از حذف <strong>${userName(user)}</strong> مطمئن هستید؟`,
    onConfirm: () => deleteMutation.mutate(user.id, { onSuccess: invalidateUsers }),
  })
}

const statusMutation = useChangeAdminUserStatusMutation()

const askStatusChange = (user, { status, title, verb }) => {
  openModal('ConfirmModal', {
    title,
    message: `آیا از ${verb} <strong>${userName(user)}</strong> مطمئن هستید؟`,
    onConfirm: () =>
      statusMutation.mutate({ id: user.id, payload: { status } }, { onSuccess: invalidateUsers }),
  })
}

const onAskBlock = (user) =>
  askStatusChange(user, { status: 'blocked', title: 'مسدود کردن کاربر', verb: 'مسدود کردن' })

const onAskUnblock = (user) =>
  askStatusChange(user, { status: 'approved', title: 'رفع مسدودیت کاربر', verb: 'رفع مسدودیت' })
</script>

<style lang="scss" scoped>
.users-page {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;

  &__heading {
    margin-bottom: 0.75rem;
  }

  &__list-header {
    display: flex;
    align-items: center;
    gap: 0.625rem;
    margin-bottom: 0.375rem;
  }

  &__list-title {
    flex: 1;
    margin-bottom: 0;
  }

  &__add-btn {
    min-width: fit-content;
    padding: 0 1.25rem;
  }
}
</style>
