import { onMounted, ref, watch } from 'vue'
import debounce from 'lodash/debounce'
import type { SortConfig } from '@/components/ui/usage/DataTable.vue'
import { useApiPagination } from '@/composables/useApiPagination'
import { getApiErrorMessage } from '@/core/utils/getApiErrorMessage'
import { listDeletedUsers } from '../services/user.service'
import type { UserListItem } from '../types/user.types'

export function useDeletedUserList(options?: { autoWatchFilters?: boolean; autoFetchOnMount?: boolean }) {
  const autoWatchFilters = options?.autoWatchFilters ?? true
  const autoFetchOnMount = options?.autoFetchOnMount ?? true
  const users = ref<UserListItem[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  const search = ref('')
  const statusFilter = ref('')
  const sortBy = ref<SortConfig[]>([{ key: 'deleted_at', order: 'desc' }])
  const page = ref(1)
  const itemsPerPage = ref(10)

  const { pagination, applyPagination } = useApiPagination({ per_page: 10 })

  async function fetchUsers(requestPage = page.value) {
    loading.value = true
    error.value = null

    try {
      const activeSort = sortBy.value[0]
      const data = await listDeletedUsers({
        page: requestPage,
        per_page: itemsPerPage.value,
        sort_by: activeSort?.key ?? 'deleted_at',
        sort_order: activeSort?.order ?? 'desc',
        search: search.value.trim() || undefined,
        status: statusFilter.value.trim() || undefined,
      })

      users.value = data.data
      applyPagination(data.pagination)
      page.value = data.pagination.current_page
    } catch (err) {
      error.value = getApiErrorMessage(err, 'Gagal memuatkan senarai pengguna yang dipadam.')
      users.value = []
    } finally {
      loading.value = false
    }
  }

  function handleSortUpdate(value: SortConfig[]) {
    sortBy.value = value
    fetchUsers(1)
  }

  const debouncedSearch = debounce(() => {
    fetchUsers(1)
  }, 400)

  if (autoWatchFilters) {
    watch(search, () => {
      debouncedSearch()
    })

    watch(statusFilter, () => {
      fetchUsers(1)
    })
  }

  watch(page, (nextPage, previousPage) => {
    if (nextPage !== previousPage) {
      fetchUsers(nextPage)
    }
  })

  watch(itemsPerPage, (nextValue, previousValue) => {
    if (nextValue !== previousValue) {
      fetchUsers(1)
    }
  })

  if (autoFetchOnMount) {
    onMounted(() => {
      fetchUsers(1)
    })
  }

  return {
    users,
    loading,
    error,
    search,
    statusFilter,
    sortBy,
    page,
    itemsPerPage,
    pagination,
    handleSortUpdate,
    fetchUsers,
  }
}
