"use client";

import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { cn } from "@/lib/utils";
import {
  ColumnDef,
  flexRender,
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  SortingState,
  useReactTable,
} from "@tanstack/react-table";
import { CalendarDays, ChevronDown, Filter, Search } from "lucide-react";
import { useMemo, useState } from "react";

export type EmployeeLeaveRow = {
  id: string;
  leaveType: string;
  from: string;
  to: string;
  days: string;
  appliedOn: string;
  status: "approved" | "pending" | "rejected";
};

const STATIC_LEAVE: EmployeeLeaveRow[] = [
  {
    id: "1",
    leaveType: "Annual leave",
    from: "Apr 2, 2026",
    to: "Apr 4, 2026",
    days: "3",
    appliedOn: "Mar 28, 2026",
    status: "approved",
  },
  {
    id: "2",
    leaveType: "Sick leave",
    from: "Mar 10, 2026",
    to: "Mar 11, 2026",
    days: "2",
    appliedOn: "Mar 9, 2026",
    status: "approved",
  },
  {
    id: "3",
    leaveType: "Casual leave",
    from: "May 20, 2026",
    to: "May 20, 2026",
    days: "1",
    appliedOn: "May 15, 2026",
    status: "pending",
  },
  {
    id: "4",
    leaveType: "Annual leave",
    from: "Feb 1, 2026",
    to: "Feb 7, 2026",
    days: "5",
    appliedOn: "Jan 22, 2026",
    status: "approved",
  },
  {
    id: "5",
    leaveType: "Work from home",
    from: "Apr 18, 2026",
    to: "Apr 18, 2026",
    days: "1",
    appliedOn: "Apr 16, 2026",
    status: "pending",
  },
  {
    id: "6",
    leaveType: "Unpaid leave",
    from: "Jan 5, 2026",
    to: "Jan 8, 2026",
    days: "4",
    appliedOn: "Dec 20, 2025",
    status: "rejected",
  },
  {
    id: "7",
    leaveType: "Annual leave",
    from: "Dec 23, 2025",
    to: "Dec 26, 2025",
    days: "2",
    appliedOn: "Dec 10, 2025",
    status: "approved",
  },
  {
    id: "8",
    leaveType: "Emergency leave",
    from: "Mar 3, 2026",
    to: "Mar 3, 2026",
    days: "1",
    appliedOn: "Mar 2, 2026",
    status: "approved",
  },
  {
    id: "9",
    leaveType: "Casual leave",
    from: "Jun 2, 2026",
    to: "Jun 3, 2026",
    days: "2",
    appliedOn: "May 30, 2026",
    status: "pending",
  },
  {
    id: "10",
    leaveType: "Annual leave",
    from: "Aug 10, 2026",
    to: "Aug 14, 2026",
    days: "5",
    appliedOn: "Jul 1, 2026",
    status: "pending",
  },
];

function StatusPill({ status }: { status: EmployeeLeaveRow["status"] }) {
  if (status === "approved") {
    return (
      <span className="inline-flex 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 === "rejected") {
    return (
      <span className="inline-flex items-center gap-1 rounded border border-[#F04438] px-2 py-0.5 text-xs font-medium text-[#F04438]">
        Rejected
        <ChevronDown className="size-3 opacity-80" aria-hidden />
      </span>
    );
  }
  return (
    <span className="inline-flex 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<EmployeeLeaveRow>[] = [
  {
    accessorKey: "id",
    header: () => <span className="capitalize">#</span>,
    cell: ({ row }) => (
      <span className="text-[13px] font-medium text-[#272833]">{row.original.id}</span>
    ),
    size: 40,
  },
  {
    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: "days",
    header: () => <span className="capitalize">Days</span>,
    cell: ({ row }) => (
      <span className="text-[13px] font-medium text-[#16151C]">{row.original.days}</span>
    ),
  },
  {
    accessorKey: "appliedOn",
    header: () => <span className="capitalize">Applied on</span>,
    cell: ({ row }) => (
      <span className="text-[13px] font-medium text-[#16151C]">{row.original.appliedOn}</span>
    ),
  },
  {
    accessorKey: "status",
    header: () => <span className="capitalize">Status</span>,
    cell: ({ row }) => <StatusPill status={row.original.status} />,
  },
];

function SummaryCard({ label, value, sub }: { label: string; value: string; sub?: string }) {
  return (
    <div className="rounded-lg border border-[#EBEEF2] bg-[#F8F9FC] px-4 py-3">
      <p className="text-xs font-medium text-[#545D69]">{label}</p>
      <p className="mt-1 text-lg font-bold text-[#1C1D22]">{value}</p>
      {sub ? <p className="text-xs text-[#858C94]">{sub}</p> : null}
    </div>
  );
}

const BlockViewEmployeeLeave = () => {
  const [sorting, setSorting] = useState<SortingState>([]);
  const [globalFilter, setGlobalFilter] = useState("");

  const stats = useMemo(() => {
    const approved = STATIC_LEAVE.filter((r) => r.status === "approved").length;
    const pending = STATIC_LEAVE.filter((r) => r.status === "pending").length;
    const rejected = STATIC_LEAVE.filter((r) => r.status === "rejected").length;
    const totalDays = STATIC_LEAVE.reduce((sum, r) => sum + Number.parseInt(r.days, 10) || 0, 0);
    return { approved, pending, rejected, totalDays, requests: STATIC_LEAVE.length };
  }, []);

  const table = useReactTable({
    data: STATIC_LEAVE,
    columns,
    state: { sorting, globalFilter },
    onSortingChange: setSorting,
    onGlobalFilterChange: setGlobalFilter,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    initialState: { pagination: { pageSize: 6 } },
    getRowId: (row) => row.id,
    globalFilterFn: (row, _id, filter) => {
      const q = String(filter).toLowerCase().trim();
      if (!q) return true;
      const r = row.original;
      return (
        r.leaveType.toLowerCase().includes(q) ||
        r.status.toLowerCase().includes(q) ||
        r.from.toLowerCase().includes(q) ||
        r.to.toLowerCase().includes(q)
      );
    },
  });

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

  return (
    <Card className="border-gray-100 shadow-sm">
      <CardContent className="space-y-6 p-4 sm:p-6">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
          <h2 className="text-lg font-bold capitalize text-[#383E49]">Leave</h2>
          <div className="flex flex-wrap items-center gap-3">
            <div className="flex h-9 min-w-[160px] max-w-full flex-1 items-center gap-2 rounded border border-[#CFD3D4] px-2 sm:max-w-[220px]">
              <Search className="size-4 shrink-0 text-[#ABAFB1]" aria-hidden />
              <Input
                placeholder="Search"
                value={globalFilter}
                onChange={(e) => setGlobalFilter(e.target.value)}
                className="h-8 border-0 bg-transparent p-0 text-xs text-[#383E49] placeholder:text-[#ABAFB1] focus-visible:ring-0"
                aria-label="Search leave requests"
              />
            </div>
            <Button
              type="button"
              variant="outline"
              className="h-9 gap-1 rounded-md border-[#E0E0E0] bg-[#FCFCFC] px-4 text-sm font-medium text-[#4F4F4F]"
              disabled
            >
              <Filter className="size-4" aria-hidden />
              Filters
            </Button>
            <Button
              type="button"
              variant="outline"
              className="h-9 gap-1 rounded-md border-[#E0E0E0] bg-[#FCFCFC] px-4 text-sm font-medium text-[#858C94]"
              disabled
            >
              <CalendarDays className="size-4" aria-hidden />
              filters
            </Button>
          </div>
        </div>

        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
          <SummaryCard label="Approved" value={String(stats.approved)} />
          <SummaryCard label="Pending" value={String(stats.pending)} />
          <SummaryCard label="Rejected" value={String(stats.rejected)} />
          <SummaryCard label="Total days (sample)" value={String(stats.totalDays)} sub={`${stats.requests} requests`} />
        </div>

        <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={columns.length} className="h-24 text-center text-[#8B8D97]">
                    No leave requests 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]"
            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]"
            onClick={() => table.nextPage()}
            disabled={!table.getCanNextPage()}
          >
            Next
          </Button>
        </div>
      </CardContent>
    </Card>
  );
};

export default BlockViewEmployeeLeave;
