import React, { Dispatch, SetStateAction } from 'react'
import {
  Badge,
  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, FiEye, FiFileText, FiTrash } from 'react-icons/fi'
import { useRouter } from 'next/navigation'

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 { capitalizeWords } from '@/lib/utils/string'
import { AgentData } from '../types'

interface DataTableProps {
  agents: AgentData[]
  isLoading?: boolean
  setModal: Dispatch<SetStateAction<ModalState<AgentData>>>
  setAgent: Dispatch<SetStateAction<AgentData | null>>
}

export default function DataTable({
  agents,
  isLoading = false,
  setModal,
  setAgent,
}: DataTableProps) {
  const router = useRouter()
  const { selectAllRows, selectedRows, toggleRowSelection, isRowSelected } =
    useTable<AgentData>()

  function handleDelete(agent: AgentData) {
    setModal({ type: 'delete', isOpened: true })
    setAgent(agent)
  }

  function handleEdit(agent: AgentData) {
    router.push(`/agents/${agent.id}/edit`)
  }

  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 === agents?.length}
                onChange={() => {
                  selectAllRows(agents)
                }}
              />
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Business Name
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Business Email
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">Category</TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Guest Market
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Contact Name
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Contact Email
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Contact Phone
            </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">
              Created By
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Updated By
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4 sticky right-0 w-20">
              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: 12 }).map((_, cellIdx) => (
                  <TableCell key={cellIdx} className="p-4">
                    <div className="h-4 bg-slate-200 rounded w-full" />
                  </TableCell>
                ))}
              </TableRow>
            ))
          ) : agents.length > 0 ? (
            agents.map((agent) => (
              <TableRow
                key={agent.id}
                className={cn('bg-white', {
                  'bg-blue-50': isRowSelected(agent),
                })}
              >
                <TableCell className="text-center p-4">
                  <Checkbox
                    color="blue"
                    checked={isRowSelected(agent)}
                    onChange={() => toggleRowSelection(agent)}
                  />
                </TableCell>

                {/* Business Name */}
                <TableCell className="text-nowrap p-4 text-black">
                  {agent.business_name}
                </TableCell>

                {/* Business Email */}
                <TableCell className="p-4 text-nowrap">
                  {agent.business_email}
                </TableCell>

                {/* Category */}
                <TableCell className="p-4 text-nowrap">
                  <Badge
                    color={agent.category === 'online' ? 'blue' : 'green'}
                    size="xs"
                    className="w-fit"
                  >
                    {capitalizeWords(agent.category)}
                  </Badge>
                </TableCell>

                {/* Guest Market */}
                <TableCell className="p-4 text-nowrap">
                  {agent.guest_market}
                </TableCell>

                {/* Contact Name */}
                <TableCell className="p-4 text-nowrap">
                  {agent.contact_person?.name || 'N/A'}
                </TableCell>

                {/* Contact Email */}
                <TableCell className="p-4 text-nowrap">
                  {agent.contact_person?.email || 'N/A'}
                </TableCell>

                {/* Contact Phone */}
                <TableCell className="p-4 text-nowrap">
                  {agent.contact_person?.phone_number || 'N/A'}
                </TableCell>

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

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

                {/* Created By */}
                <TableCell className="p-4 text-nowrap">
                  {agent.created_by?.name || 'N/A'}
                </TableCell>

                {/* Updated By */}
                <TableCell className="p-4 text-nowrap">
                  {agent.updated_by?.name || 'N/A'}
                </TableCell>

                <TableCell className="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(agent)
                      }}
                    >
                      Delete
                    </DropdownItem>
                    <DropdownDivider />
                    <DropdownItem
                      icon={FiEdit}
                      onClick={() => handleEdit(agent)}
                    >
                      Edit
                    </DropdownItem>
                    <DropdownDivider />
                    <DropdownItem
                      icon={FiEye}
                      onClick={() => router.push(`/agents/${agent.id}`)}
                    >
                      View Details
                    </DropdownItem>
                    {agent.agreement_document_url && (
                      <React.Fragment>
                        <DropdownDivider />
                        <DropdownItem
                          icon={FiFileText}
                          as="a"
                          href={agent.agreement_document_url}
                          target="_blank"
                          rel="noopener noreferrer"
                        >
                          View Agreement
                        </DropdownItem>
                      </React.Fragment>
                    )}
                  </Dropdown>
                </TableCell>
              </TableRow>
            ))
          ) : (
            <TableRow>
              <TableCell colSpan={13} className="text-center p-8">
                No data available
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>
    </div>
  )
}
