import React, { Dispatch, SetStateAction } from 'react'
import { isSameDay } from 'date-fns'
import { HiOutlineDotsHorizontal } from 'react-icons/hi'
import { FiGrid, FiTrash } from 'react-icons/fi'
import { useRouter } from 'next/navigation'
import {
  Avatar,
  Badge,
  Checkbox,
  Dropdown,
  DropdownDivider,
  DropdownItem,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeadCell,
  TableRow,
} from 'flowbite-react'

import avatarTheme from '@/lib/themes/avatar'
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 { Merchant } from '../types'
import { TbUserEdit } from 'react-icons/tb'
import { useAuth } from '@/lib/context/AuthContext'

interface DataTableProps {
  merchants: Merchant[]
  isLoading?: boolean
  setModal: Dispatch<SetStateAction<ModalState>>
  setMerchant: Dispatch<SetStateAction<Merchant | null>>
}

export default function DataTable({
  merchants,
  isLoading = false,
  setModal,
  setMerchant,
}: DataTableProps) {
  const router = useRouter()
  const { user } = useAuth()
  const { selectAllRows, selectedRows, toggleRowSelection, isRowSelected } =
    useTable<Merchant>()

  function handleDelete(merchant: Merchant) {
    setModal({ type: 'delete', isOpened: true })
    setMerchant(merchant)
  }

  function handleEdit(merchant: Merchant) {
    setModal({ type: 'edit', isOpened: true })
    setMerchant(merchant)
  }

  return (
    <div className="overflow-x-auto mt-4 min-h-48">
      <Table theme={tableTheme.table} hoverable>
        <TableHead>
          <TableRow>
            <TableHeadCell className="text-center p-4">
              <Checkbox
                color="blue"
                checked={selectedRows.length === merchants?.length}
                onChange={() => {
                  selectAllRows(merchants)
                }}
              />
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">Merchant</TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">Username</TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">Code</TableHeadCell>
            {user?.role === 'super_admin' && (
              <React.Fragment>
                <TableHeadCell className="text-nowrap p-4">
                  Created At
                </TableHeadCell>
                <TableHeadCell className="text-nowrap p-4">
                  Updated At
                </TableHeadCell>
              </React.Fragment>
            )}
            <TableHeadCell className="text-nowrap p-4 sticky right-0 w-fit ml-auto text-right">
              Action
            </TableHeadCell>
          </TableRow>
        </TableHead>

        <TableBody className="divide-y divide-gray-200">
          {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>

                <TableCell className="p-4 flex items-center gap-4">
                  <div className="w-10 h-10 rounded-full bg-slate-200" />
                  <div className="h-4 w-[100px] bg-slate-200 rounded" />
                </TableCell>

                <TableCell className="p-4">
                  <div className="h-4 w-[100px] bg-slate-200 rounded" />
                </TableCell>

                <TableCell className="p-4">
                  <div className="h-4 w-[100px] bg-slate-200 rounded" />
                </TableCell>

                {user?.role === 'super_admin' && (
                  <React.Fragment>
                    <TableCell className="p-4">
                      <div className="h-4 w-[100px] bg-slate-200 rounded" />
                    </TableCell>

                    <TableCell className="p-4">
                      <div className="h-4 w-[100px] bg-slate-200 rounded" />
                    </TableCell>
                  </React.Fragment>
                )}

                <TableCell className="p-4">
                  <div className="h-4 w-[50px] bg-slate-200 rounded ml-auto" />
                </TableCell>
              </TableRow>
            ))
          ) : merchants?.length > 0 ? (
            merchants.map((merchant) => (
              <TableRow
                key={merchant.id}
                className={cn('bg-white', {
                  'bg-gray-100': isRowSelected(merchant),
                })}
              >
                <TableCell className="text-center p-4">
                  <Checkbox
                    color="blue"
                    checked={isRowSelected(merchant)}
                    onChange={() => toggleRowSelection(merchant)}
                  />
                </TableCell>

                {/* Merchant */}
                <TableCell className="p-4">
                  <Avatar
                    theme={{
                      ...avatarTheme,
                      root: {
                        ...avatarTheme.root,
                        inner: `${avatarTheme.root.inner} h-8 w-8`,
                      },
                    }}
                    alt="User Avatar"
                    img={`https://api.dicebear.com/9.x/initials/svg?seed=${merchant?.name}&backgroundType=gradientLinear`}
                    rounded
                    size="sm"
                    className="w-fit"
                  >
                    <span className="text-black font-medium text-nowrap">
                      {merchant?.name}
                    </span>
                  </Avatar>
                </TableCell>

                {/* Merchant Username */}
                <TableCell className="p-4">{merchant?.username}</TableCell>

                {/* Merchant Code */}
                <TableCell className="p-4">
                  <Badge color="light" className="text-xs font-medium w-fit">
                    {merchant?.code}
                  </Badge>
                </TableCell>

                {user?.role === 'super_admin' && (
                  <React.Fragment>
                    {/* Created At */}
                    <TableCell
                      className={`p-4 text-nowrap ${isSameDay(new Date(), new Date(merchant?.created_at)) ? 'text-green-600 font-medium' : ''}`}
                    >
                      {formatToMYT(merchant?.created_at)}
                    </TableCell>

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

                {/* Action */}
                <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}
                  >
                    {user?.role === 'super_admin' && (
                      <React.Fragment>
                        <DropdownItem
                          icon={TbUserEdit}
                          onClick={() => {
                            handleEdit(merchant)
                          }}
                        >
                          Edit Admins
                        </DropdownItem>
                        <DropdownDivider />
                        <DropdownItem
                          icon={FiTrash}
                          onClick={() => {
                            handleDelete(merchant)
                          }}
                        >
                          Delete
                        </DropdownItem>
                      </React.Fragment>
                    )}

                    {user?.role !== 'super_admin' && (
                      <DropdownItem
                        icon={FiGrid}
                        onClick={() => {
                          router.push(`/merchant-dashboard/${merchant?.id}`)
                        }}
                      >
                        Open Dashboard
                      </DropdownItem>
                    )}
                  </Dropdown>
                </TableCell>
              </TableRow>
            ))
          ) : (
            <TableRow>
              <TableCell colSpan={8} className="text-center p-4">
                No data available
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>
    </div>
  )
}
