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

export function useActivityLogList() {
  const activityLogs = ref<ActivityLogItem[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  const search = ref('')
  const page = ref(1)
  const itemsPerPage = ref(10)

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

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

    try {
      const data = await listActivityLogs({
        page: requestPage,
        per_page: itemsPerPage.value,
        search: search.value.trim() || undefined,
      })

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

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

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

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

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

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

  return {
    activityLogs,
    loading,
    error,
    search,
    page,
    itemsPerPage,
    pagination,
    fetchActivityLogs,
  }
}
