import React from 'react'
import { FiEye } from 'react-icons/fi'
import { HiOutlineDotsHorizontal } from 'react-icons/hi'
import {
  Checkbox,
  Table,
  Dropdown,
  TableHead,
  TableHeadCell,
  TableRow,
  TableBody,
  TableCell,
  DropdownItem,
  Badge,
} from 'flowbite-react'
import { useRouter } from 'next/navigation'

import { useTable } from '@/lib/hooks/useTable'
import tableTheme from '@/lib/themes/table'
import { cn } from '@/lib/utils/tw-merge'
import { formatDateToLongFormat } from '@/lib/utils/date'
import { formatIDR } from '@/lib/utils/currency'
import {
  PAYMENT_CHANNEL_LABELS,
  PAYMENT_METHOD_LABELS,
  PAYMENT_STATUS_BADGE_LABELS,
  PAYMENT_STATUS_LABELS,
} from '@/lib/types/payment'
import { Order } from '../../orders/types'
import { useMerchant } from '@/lib/context/MerchantContext'
import badgeTheme from '@/lib/themes/badge'

interface DataTableProps {
  sales: Order[]
  isLoading?: boolean
}

export default function DataTable({ sales, isLoading }: DataTableProps) {
  const router = useRouter()
  const { merchant } = useMerchant()
  const { selectAllRows, selectedRows, toggleRowSelection, isRowSelected } =
    useTable<Order>()

  return (
    <div className="overflow-x-auto mt-10 min-h-48">
      <Table theme={tableTheme.table}>
        <TableHead>
          <TableRow>
            <TableHeadCell className="p-4 text-center">
              <Checkbox
                color="blue"
                checked={selectedRows.length === sales?.length}
                onChange={() => {
                  selectAllRows(sales)
                }}
              />
            </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">Sub Total</TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">Surcharge</TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Total Payment
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Transaction Fee
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Total Sales
            </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 sticky right-0">
              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: 11 }).map((_, cellIdx) => (
                  <TableCell key={cellIdx} className="text-center p-4">
                    <div className="w-full h-4 rounded bg-slate-200 mx-auto" />
                  </TableCell>
                ))}
              </TableRow>
            ))
          ) : sales.length > 0 ? (
            sales.map((sale) => (
              <TableRow
                key={sale.id}
                className={cn('bg-white', {
                  'bg-gray-100': isRowSelected(sale),
                })}
              >
                <TableCell className="p-4 text-center">
                  <Checkbox
                    color="blue"
                    checked={isRowSelected(sale)}
                    onChange={() => toggleRowSelection(sale)}
                  />
                </TableCell>

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

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

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

                {/* Sub Total */}
                <TableCell className="text-nowrap p-4">
                  {formatIDR(Number(sale.sub_total ?? 0))}
                </TableCell>

                {/* Total Surcharge */}
                <TableCell className="text-nowrap p-4">
                  {formatIDR(Number(sale.surcharge ?? 0))}
                </TableCell>

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

                {/* Transaction Fee */}
                <TableCell className="text-nowrap p-4">
                  {formatIDR(Number(sale.transaction_fee ?? 0))}
                </TableCell>

                {/* Total Sales */}
                <TableCell className="text-nowrap p-4">
                  {formatIDR(Number(sale.total_sales ?? 0))}
                </TableCell>

                {/* Payment Method */}
                <TableCell className="text-nowrap p-4">
                  {PAYMENT_METHOD_LABELS[sale.payment_method_code]}{' '}
                  {/* Payment Channel Detail */}
                  {sale.payment_channel_code === null
                    ? ''
                    : `(${PAYMENT_CHANNEL_LABELS[sale.payment_channel_code]})`}
                  {/* Account Reference Detail */}
                  {sale.account_reference === null
                    ? ''
                    : `(Acc Ref: ${sale.account_reference?.invoice_number})`}
                </TableCell>

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

                {/* Actions */}
                <TableCell className="flex text-nowrap sticky right-0 gap-2 p-4 bg-gray-100 z-2">
                  <Dropdown
                    label={<HiOutlineDotsHorizontal />}
                    placement="left-start"
                    arrowIcon={false}
                    color="alternative"
                    theme={tableTheme.dropdown}
                  >
                    <DropdownItem
                      icon={FiEye}
                      onClick={() =>
                        router.push(
                          `/merchant-dashboard/${merchant?.id}/sales/${sale.id}`,
                        )
                      }
                    >
                      View
                    </DropdownItem>
                  </Dropdown>
                </TableCell>
              </TableRow>
            ))
          ) : (
            <TableRow>
              <TableCell colSpan={13} className="text-center p-8">
                No sales found.
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>
    </div>
  )
}
