import { Dispatch, SetStateAction } from 'react'
import {
  Checkbox,
  Dropdown,
  DropdownDivider,
  DropdownItem,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeadCell,
  TableRow,
} from 'flowbite-react'
import { isSameDay } from 'date-fns'
import { HiOutlineDotsHorizontal } from 'react-icons/hi'
import { FiEdit, FiTrash } from 'react-icons/fi'

import tableTheme from '@/lib/themes/table'
import { useTable } from '@/lib/hooks/useTable'
import { cn } from '@/lib/utils/tw-merge'
import { formatToMYT } from '@/lib/utils/date'
import { Marketplace } from '../types'

interface DataTableProps {
  marketplaces: Marketplace[]
  isLoading?: boolean
  setModal: Dispatch<SetStateAction<ModalState<Marketplace>>>
  setMarketplace: Dispatch<SetStateAction<Marketplace | null>>
  onEdit: (marketplace: Marketplace) => void
}

export default function DataTable({
  marketplaces,
  isLoading = false,
  setModal,
  setMarketplace,
  onEdit,
}: DataTableProps) {
  const { selectAllRows, selectedRows, toggleRowSelection, isRowSelected } =
    useTable<Marketplace>()

  function handleDelete(marketplace: Marketplace) {
    setModal({
      type: 'delete',
      isOpened: true,
      processing: false,
      data: marketplace,
    })

    setMarketplace(marketplace)
  }

  function handleEdit(marketplace: Marketplace) {
    setModal({
      type: 'edit',
      isOpened: true,
      processing: false,
      data: marketplace,
    })

    setMarketplace(marketplace)

    onEdit(marketplace)
  }

  return (
    <div className="overflow-x-auto mt-10 min-h-48">
      <Table theme={tableTheme.table} hoverable>
        <TableHead>
          <TableRow>
            <TableHeadCell className="text-center p-4">
              <Checkbox
                color="blue"
                checked={selectedRows.length === marketplaces?.length}
                onChange={() => {
                  selectAllRows(marketplaces)
                }}
              />
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Marketplace Name
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Created At
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Updated At
            </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 mx-auto" />
                </TableCell>

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

                {/* Marketplace Name */}
                <TableCell className="text-nowrap p-4 text-black font-medium">
                  {marketplace.name}
                </TableCell>

                {/* Created At */}
                <TableCell
                  className={`p-4 text-nowrap ${isSameDay(new Date(), new Date(marketplace.created_at as string)) ? 'text-green-600 font-medium' : ''}`}
                >
                  {formatToMYT(marketplace.created_at)}
                </TableCell>

                {/* Updated At */}
                <TableCell
                  className={`p-4 text-nowrap ${isSameDay(new Date(), new Date(marketplace.updated_at as string)) ? 'text-green-600 font-medium' : ''}`}
                >
                  {formatToMYT(marketplace.updated_at)}
                </TableCell>

                <TableCell className="flex text-nowrap sticky right-0 gap-2 p-4 bg-gray-100 z-2 w-fit ml-auto">
                  <Dropdown
                    label={<HiOutlineDotsHorizontal />}
                    placement="left-start"
                    arrowIcon={false}
                    color="alternative"
                    theme={tableTheme.dropdown}
                  >
                    <DropdownItem
                      icon={FiTrash}
                      onClick={() => {
                        handleDelete(marketplace)
                      }}
                    >
                      Delete
                    </DropdownItem>
                    <DropdownDivider />
                    <DropdownItem
                      icon={FiEdit}
                      onClick={() => handleEdit(marketplace)}
                    >
                      Edit
                    </DropdownItem>
                  </Dropdown>
                </TableCell>
              </TableRow>
            ))
          ) : (
            <TableRow>
              <TableCell colSpan={5} className="text-center p-8">
                No data available
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>
    </div>
  )
}
