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 { listUsers } from '../services/user.service'
import type { UserListItem } from '../types/user.types'

export function useUserList() {
  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: 'name', order: 'asc' }])
  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 listUsers({
        page: requestPage,
        per_page: itemsPerPage.value,
        sort_by: activeSort?.key ?? 'name',
        sort_order: activeSort?.order ?? 'asc',
        search: search.value.trim() || undefined,
        status: statusFilter.value.trim() || undefined,
      })

      users.value = data.data
      applyPagination(data.pagination)
      page.value = data.pagination.current_page
    } finally {
      loading.value = false
    }
  }

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

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

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

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

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