"use client";

import { Button } from "@/components/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { cn } from "@/lib/utils";
import type { HolidayRow, HolidayStatus } from "@/types/holiday";
import {
  ColumnDef,
  flexRender,
  getCoreRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  RowSelectionState,
  SortingState,
  useReactTable,
} from "@tanstack/react-table";
import { ChevronDown, MoreVertical } from "lucide-react";
import Image from "next/image";
import { useMemo, useState } from "react";

function StatusPill({ status }: { status: HolidayStatus }) {
  if (status === "approved") {
    return (
      <span className="inline-flex cursor-default items-center gap-1 rounded border border-[#039855] px-2 py-0.5 text-xs font-medium text-[#039855]">
        Approved
        <ChevronDown className="size-3 opacity-80" aria-hidden />
      </span>
    );
  }
  if (status === "declined") {
    return (
      <span className="inline-flex cursor-default items-center gap-1 rounded border border-[#F04438] px-2 py-0.5 text-xs font-medium text-[#F04438]">
        Declined
        <ChevronDown className="size-3 opacity-80" aria-hidden />
      </span>
    );
  }
  return (
    <span className="inline-flex cursor-default items-center gap-1 rounded border border-[#F79009] px-2 py-0.5 text-xs font-medium text-[#B54708]">
      Pending
      <ChevronDown className="size-3 opacity-80" aria-hidden />
    </span>
  );
}

const columns: ColumnDef<HolidayRow>[] = [
  {
    id: "select",
    header: ({ table }) => (
      <div className="flex justify-center">
        <input
          type="checkbox"
          className="size-4 cursor-pointer rounded-sm border border-[#074473] accent-[#074473]"
          checked={table.getIsAllPageRowsSelected()}
          onChange={table.getToggleAllPageRowsSelectedHandler()}
          aria-label="Select all on this page"
        />
      </div>
    ),
    cell: ({ row }) => (
      <div className="flex justify-center">
        <input
          type="checkbox"
          className="size-4 cursor-pointer rounded-sm border border-[#074473] accent-[#074473]"
          checked={row.getIsSelected()}
          onChange={row.getToggleSelectedHandler()}
          aria-label={`Select ${row.original.employeeName}`}
        />
      </div>
    ),
    enableSorting: false,
    size: 48,
  },
  {
    accessorKey: "image",
    header: () => <span className="capitalize">Image</span>,
    cell: ({ row }) => (
      <Image
        className="size-11 rounded-xl bg-[#E6ECF1] object-cover"
        alt=""
        src={row.original.image}
        width={45}
        height={45}
      />
    ),
    enableSorting: false,
  },
  {
    accessorKey: "employeeName",
    header: () => <span className="capitalize">Employee Name</span>,
    cell: ({ row }) => (
      <span className="text-[13px] font-medium text-[#272833]">{row.original.employeeName}</span>
    ),
  },
  {
    accessorKey: "leaveType",
    header: () => <span className="capitalize">Leave Type</span>,
    cell: ({ row }) => (
      <span className="text-[13px] font-medium text-[#272833]">{row.original.leaveType}</span>
    ),
  },
  {
    accessorKey: "from",
    header: () => <span className="capitalize">From</span>,
    cell: ({ row }) => (
      <span className="text-[13px] font-medium text-[#16151C]">{row.original.from}</span>
    ),
  },
  {
    accessorKey: "to",
    header: () => <span className="capitalize">To</span>,
    cell: ({ row }) => (
      <span className="text-[13px] font-medium text-[#16151C]">{row.original.to}</span>
    ),
  },
  {
    accessorKey: "daysLabel",
    header: () => <span>No. Of Days</span>,
    cell: ({ row }) => (
      <span className="text-[13px] font-medium text-[#16151C]">{row.original.daysLabel}</span>
    ),
  },
  {
    accessorKey: "reason",
    header: () => <span className="capitalize">Reason</span>,
    cell: ({ row }) => (
      <span className="text-[13px] font-medium text-[#16151C]">{row.original.reason}</span>
    ),
  },
  {
    accessorKey: "status",
    header: () => <span className="capitalize">Status</span>,
    cell: ({ row }) => <StatusPill status={row.original.status} />,
  },
  {
    id: "actions",
    header: () => <span className="capitalize">Action</span>,
    cell: () => (
      <Button
        type="button"
        variant="ghost"
        size="icon"
        className="size-8 text-[#858C94] hover:bg-[#F4F5FA] hover:text-[#383E49]"
        aria-label="Row actions"
      >
        <MoreVertical className="size-4" aria-hidden />
      </Button>
    ),
    enableSorting: false,
  },
];

type Props = {
  data: HolidayRow[];
};

export default function LeavesFilledPanel({ data }: Props) {
  const [sorting, setSorting] = useState<SortingState>([]);
  const [rowSelection, setRowSelection] = useState<RowSelectionState>({});

  const tableColumns = useMemo(() => columns, []);

  const table = useReactTable({
    data,
    columns: tableColumns,
    state: { sorting, rowSelection },
    onSortingChange: setSorting,
    onRowSelectionChange: setRowSelection,
    enableRowSelection: true,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    initialState: { pagination: { pageSize: 10 } },
    getRowId: (row) => row.id,
  });

  const pageCount = Math.max(1, table.getPageCount());
  const pageIndex = table.getState().pagination.pageIndex;

  return (
    <div className="space-y-6">
      <div className="overflow-hidden rounded-md border border-[#EBEEF2] bg-white">
        <Table>
          <TableHeader>
            {table.getHeaderGroups().map((headerGroup) => (
              <TableRow key={headerGroup.id} className="border-0 hover:bg-transparent">
                {headerGroup.headers.map((header) => (
                  <TableHead
                    key={header.id}
                    className={cn(
                      "h-12 bg-white px-3 py-3 text-left text-sm font-bold capitalize text-[#272833]",
                      "first:pl-4 last:pr-4",
                    )}
                  >
                    {header.isPlaceholder
                      ? null
                      : flexRender(header.column.columnDef.header, header.getContext())}
                  </TableHead>
                ))}
              </TableRow>
            ))}
          </TableHeader>
          <TableBody>
            {table.getRowModel().rows.length ? (
              table.getRowModel().rows.map((row) => (
                <TableRow
                  key={row.id}
                  className="border-b border-[#EBEEF2] last:border-0 hover:bg-[#F9FAFB]"
                >
                  {row.getVisibleCells().map((cell) => (
                    <TableCell key={cell.id} className="px-3 py-3 align-middle first:pl-4 last:pr-4">
                      {flexRender(cell.column.columnDef.cell, cell.getContext())}
                    </TableCell>
                  ))}
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell colSpan={tableColumns.length} className="h-24 text-center text-[#8B8D97]">
                  No holidays match your search.
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>

      <div className="flex flex-col items-stretch justify-center gap-4 sm:flex-row sm:items-center sm:justify-between">
        <Button
          type="button"
          variant="outline"
          className="h-[34px] rounded-md border border-[#E0E0E0] bg-[#FCFCFC] px-6 text-xs font-medium text-[#4F4F4F] hover:bg-[#FCFCFC]"
          onClick={() => table.previousPage()}
          disabled={!table.getCanPreviousPage()}
        >
          Previous
        </Button>
        <p className="text-center text-xs font-medium capitalize text-[#858C94] opacity-70">
          page {pageIndex + 1} of {pageCount}
        </p>
        <Button
          type="button"
          variant="outline"
          className="h-[34px] rounded-md border border-[#E0E0E0] bg-[#FCFCFC] px-6 text-xs font-medium text-[#4F4F4F] hover:bg-[#FCFCFC]"
          onClick={() => table.nextPage()}
          disabled={!table.getCanNextPage()}
        >
          Next
        </Button>
      </div>
    </div>
  );
}
