import { onMounted, ref, watch } from 'vue'
import debounce from 'lodash/debounce'
import { useApiPagination } from '@/composables/useApiPagination'
import { getApiErrorMessage } from '@/core/utils/getApiErrorMessage'
import { listActivities } from '../services/activity.service'
import type { ActivityListItem } from '../types/activity.types'

export function useActivityList() {
  const activities = ref<ActivityListItem[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  const search = ref('')
  const page = ref(1)
  const itemsPerPage = ref(10)
  const sortBy = ref('start_datetime')
  const sortOrder = ref<'asc' | 'desc'>('desc')

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

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

    try {
      const data = await listActivities({
        page: requestPage,
        per_page: itemsPerPage.value,
        sort_by: sortBy.value,
        sort_order: sortOrder.value,
        search: search.value.trim() || undefined,
      })

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

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

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

  watch([sortBy, sortOrder], () => {
    fetchActivities(1)
  })

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

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

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

  return {
    activities,
    loading,
    error,
    search,
    page,
    itemsPerPage,
    sortBy,
    sortOrder,
    pagination,
    fetchActivities,
  }
}
