import { useEffect, useState } from 'react'
import {
  PaginationState,
  SortingState,
  getCoreRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
} from '@tanstack/react-table'

import { useUserStore } from '@/src/store/userStore'
import { useColumns } from './useColumns'
import {
  useDownloadPaymentReport,
  useFetchPayments,
} from '@/src/hooks/user/payments'
import { useUIStore } from '@/src/store/uiStore'

export const usePaymentsTable = () => {
  const [isModalDeleteOpen, setModalDeleteOpen] = useState(false)
  const { setPaymentSelected, clearPaymentSelected } = useUserStore()
  const { setLoading } = useUIStore()
  const {
    mutate: downloadPaymentReportMutate,
    isLoading: downloadPaymentReportIsLoading,
  } = useDownloadPaymentReport()

  const handleDownloadPaymentReport = async (payment: string) => {
    downloadPaymentReportMutate({ id: payment }, {
      onSuccess: data => {
        const { report } = data.data
        window.open(report, '_blank')
      },
    })
  }

  const handleOpenModalDelete = (payment: string) => {
    setPaymentSelected(payment)
    setModalDeleteOpen(true)
  }
  const handleCloseModalDelete = () => {
    clearPaymentSelected()
    setModalDeleteOpen(false)
  }

  const columns = useColumns({
    onDownloadPaymentReport: handleDownloadPaymentReport,
    onOpenDeleteModal: handleOpenModalDelete,
  })

  const [sorting, setSorting] = useState<SortingState>([])
  const [search, setSearch] = useState('')

  const [pagination, setPagination] = useState<PaginationState>({
    pageIndex: 0,
    pageSize: 10,
  })

  const {
    data,
    refetch,
    isLoading: fetchIsLoading,
  } = useFetchPayments({
    page: pagination.pageIndex + 1,
    pageSize: pagination.pageSize,
    search,
    sort: sorting.length
      ? `${sorting[0].id}:${sorting[0].desc ? 'desc' : 'asc'}`
      : '',
  })

  useEffect(() => {
    setLoading(fetchIsLoading || downloadPaymentReportIsLoading)
  }, [fetchIsLoading, downloadPaymentReportIsLoading])

  useEffect(() => {
    refetch()
  }, [pagination.pageIndex, pagination.pageSize, sorting, search])

  const { getHeaderGroups, getRowModel, setPageSize, getState, getPageCount } =
    useReactTable({
      columns,
      data: data?.payments || [],
      getCoreRowModel: getCoreRowModel(),
      getSortedRowModel: getSortedRowModel(),
      onSortingChange: setSorting,
      getPaginationRowModel: getPaginationRowModel(),
      onPaginationChange: setPagination,
      state: {
        sorting,
        pagination,
      },
      manualPagination: true,
      pageCount: data?.totalPages ? data?.totalPages - 1 : 1,
    })

  return {
    search,
    columns,
    pagination,
    data,
    setPageSize,
    setSearch,
    getHeaderGroups,
    getRowModel,
    getState,
    getPageCount,
    setPagination,
    isModalDeleteOpen,
    handleCloseModalDelete,
  }
}
