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 { listFeedback } from '../services/feedback.service'
import type {
  FeedbackListItem,
  FeedbackPriority,
  FeedbackStatus,
  FeedbackType,
} from '../types/feedback.types'

export function useFeedbackList() {
  const items = ref<FeedbackListItem[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  const search = ref('')
  const typeFilter = ref<FeedbackType | ''>('')
  const statusFilter = ref<FeedbackStatus | ''>('')
  const priorityFilter = ref<FeedbackPriority | ''>('')
  const sortBy = ref<SortConfig[]>([{ key: 'created_at', order: 'desc' }])
  const page = ref(1)
  const itemsPerPage = ref(10)

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

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

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

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

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

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

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

  watch([typeFilter, statusFilter, priorityFilter], () => {
    fetchItems(1)
  })

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

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

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

  return {
    items,
    loading,
    error,
    search,
    typeFilter,
    statusFilter,
    priorityFilter,
    sortBy,
    page,
    itemsPerPage,
    pagination,
    handleSortUpdate,
    fetchItems,
  }
}
