import React, { useState } from 'react'
import { toast } from 'react-toastify'
import { HiOutlineDotsHorizontal } from 'react-icons/hi'
import {
  Checkbox,
  Table,
  Dropdown,
  TableHead,
  TableHeadCell,
  TableBody,
  TableRow,
  TableCell,
  Badge,
  DropdownItem,
} from 'flowbite-react'
import { LuDownload } from 'react-icons/lu'

import {
  PAYMENT_STATUS_LABELS,
  PAYMENT_METHOD_LABELS,
  PAYMENT_CHANNEL_LABELS,
  PAYMENT_STATUS_BADGE_LABELS,
} from '@/lib/types/payment'
import { useTable } from '@/lib/hooks/useTable'
import { cn } from '@/lib/utils/tw-merge'
import { formatDateToLongFormat } from '@/lib/utils/date'
import { formatIDR } from '@/lib/utils/currency'
import badgeTheme from '@/lib/themes/badge'
import * as transactionServices from '@/lib/services/transaction-services'
import tableTheme from '@/lib/themes/table'
import * as fileServices from '@/lib/services/file-services'
import FullPageLoader from '@/lib/components/FullPageLoader'
import { Transaction } from '@/lib/types/transaction'
import { SearchFormProps } from '../types'

interface DataTableProps {
  transactions: Transaction[]
  isLoading?: boolean
  searchForm: Partial<SearchFormProps>
}

export default function DataTable({
  transactions,
  isLoading = false,
}: DataTableProps) {
  const [isDownloadingPdf, setIsDownloadingPdf] = useState(false)
  const [downloadPdfMessage, setDownloadPdfMessage] = useState('')
  const { selectAllRows, selectedRows, toggleRowSelection, isRowSelected } =
    useTable<Transaction>()

  async function handleDownloadComissionReceipt(transaction: Transaction) {
    try {
      setIsDownloadingPdf(true)
      setDownloadPdfMessage('Downloading Commission Receipt...')

      const commissionReceiptFileUrl =
        transactionServices.getCommissionReceiptFileUrl(transaction.id)

      await fileServices.downloadDocument({
        url: commissionReceiptFileUrl,
        filenameFallback: `commission-${transaction.invoice_number}.pdf`,
      })
    } catch {
      toast.error('Failed to download Commission Receipt.')
    } finally {
      setIsDownloadingPdf(false)
      setDownloadPdfMessage('')
    }
  }

  if (isDownloadingPdf) {
    return <FullPageLoader message={downloadPdfMessage} />
  }

  return (
    <div className="overflow-x-auto mt-10 min-h-48">
      <Table theme={tableTheme.table} hoverable>
        <TableHead>
          <TableRow>
            <TableHeadCell className="p-4 text-center">
              <Checkbox
                color="blue"
                checked={selectedRows.length === transactions?.length}
                onChange={() => {
                  selectAllRows(transactions)
                }}
              />
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Invoice Number
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Transaction Date
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Billing Name
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Payment Method
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Payment Status
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Total Payment
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Total Commission
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4 sticky right-0 w-fit ml-auto text-right">
              Action
            </TableHeadCell>
          </TableRow>
        </TableHead>

        <TableBody>
          {isLoading ? (
            Array.from({ length: 6 }).map((_, idx) => (
              <TableRow key={`sk-${idx}`} className="bg-white animate-pulse">
                <TableCell className="text-center p-4">
                  <div className="w-4 h-4 bg-slate-200 rounded" />
                </TableCell>

                {Array.from({ length: 8 }).map((_, cellIdx) => (
                  <TableCell key={cellIdx} className="text-center p-4">
                    <div className="w-full h-4 rounded bg-slate-200 mx-auto" />
                  </TableCell>
                ))}
              </TableRow>
            ))
          ) : transactions.length > 0 ? (
            transactions?.map((transaction) => (
              <TableRow
                key={transaction.id}
                className={cn('bg-white', {
                  'bg-gray-100': isRowSelected(transaction),
                })}
              >
                <TableCell className="p-4 text-center">
                  <Checkbox
                    color="blue"
                    checked={isRowSelected(transaction)}
                    onChange={() => toggleRowSelection(transaction)}
                  />
                </TableCell>

                {/* Invoice Number */}
                <TableCell className="text-nowrap font-medium text-black p-4">
                  {transaction.invoice_number}
                </TableCell>

                {/* Date */}
                <TableCell className="text-nowrap p-4">
                  {formatDateToLongFormat(transaction.transaction_date)}
                </TableCell>

                {/* Billing Name */}
                <TableCell className="text-nowrap p-4">
                  {transaction.billing_name}
                </TableCell>

                {/* Payment Method */}
                <TableCell className="text-nowrap p-4">
                  {PAYMENT_METHOD_LABELS[transaction.payment_method_code]}{' '}
                  {transaction.payment_channel_code === null
                    ? ''
                    : `(${PAYMENT_CHANNEL_LABELS[transaction.payment_channel_code]})`}
                </TableCell>

                {/* Payment Status */}
                <TableCell className="text-nowrap p-4">
                  <Badge
                    className={`w-fit bg-${PAYMENT_STATUS_BADGE_LABELS[transaction.payment_status]}-100 text-${PAYMENT_STATUS_BADGE_LABELS[transaction.payment_status]}-600`}
                    theme={badgeTheme.badge}
                    color="none"
                  >
                    {PAYMENT_STATUS_LABELS[transaction.payment_status]}
                  </Badge>
                </TableCell>

                {/* Total Payment */}
                <TableCell className="text-nowrap p-4">
                  {formatIDR(Number(transaction.total_amount ?? 0))}
                </TableCell>

                {/* Total Commission */}
                <TableCell className="text-nowrap p-4">
                  {formatIDR(Number(transaction.net_tp_commission ?? 0))}
                </TableCell>

                {/* Actions */}
                <TableCell className="flex text-nowrap sticky right-0 gap-2 p-4 bg-gray-100 border-b-0! w-fit ml-auto">
                  <Dropdown
                    label={<HiOutlineDotsHorizontal />}
                    placement="left-start"
                    arrowIcon={false}
                    color="alternative"
                    theme={tableTheme.dropdown}
                  >
                    {(transaction.payment_status === 'SUCCESS' ||
                      transaction.payment_status === 'PARTIALLY_REFUNDED' ||
                      transaction.payment_status === 'FULLY_REFUNDED') && (
                      <React.Fragment>
                        <DropdownItem
                          icon={LuDownload}
                          onClick={handleDownloadComissionReceipt.bind(
                            null,
                            transaction,
                          )}
                        >
                          Commission Receipt
                        </DropdownItem>
                      </React.Fragment>
                    )}
                  </Dropdown>
                </TableCell>
              </TableRow>
            ))
          ) : (
            <TableRow>
              <TableCell colSpan={9} className="text-center p-8">
                No transactions found.
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>
    </div>
  )
}
