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 { listMembershipApplications } from '../services/membership-application.service'
import type { MembershipApplicationListItem } from '../types/membership-application.types'

export function useMembershipApplicationList() {
  const applications = ref<MembershipApplicationListItem[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  const search = ref('')
  const statusFilter = ref('')
  const sortBy = ref<SortConfig[]>([{ key: 'submitted_at', order: 'desc' }])
  const page = ref(1)
  const itemsPerPage = ref(10)

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

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

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

      applications.value = data.data
      applyPagination(data.pagination)
      page.value = data.pagination.current_page
    } catch (err) {
      error.value = getApiErrorMessage(err, 'Gagal memuatkan senarai permohonan keahlian.')
      applications.value = []
    } finally {
      loading.value = false
    }
  }

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

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

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

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

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

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

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

  return {
    applications,
    loading,
    error,
    search,
    statusFilter,
    sortBy,
    page,
    itemsPerPage,
    pagination,
    handleSortUpdate,
    fetchApplications,
  }
}
