"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 EmployeeProjectRow = {
  id: string;
  projectName: string;
  client: string;
  role: string;
  startDate: string;
  endDate: string;
  status: "in-progress" | "completed" | "on-hold";
  progress: string;
};

const STATIC_PROJECTS: EmployeeProjectRow[] = [
  {
    id: "1",
    projectName: "HR Portal redesign",
    client: "Nizamify HQ",
    role: "Lead",
    startDate: "Jan 8, 2026",
    endDate: "Jun 30, 2026",
    status: "in-progress",
    progress: "62%",
  },
  {
    id: "2",
    projectName: "Payroll integration",
    client: "Finance Ops",
    role: "Contributor",
    startDate: "Feb 1, 2026",
    endDate: "Apr 15, 2026",
    status: "in-progress",
    progress: "40%",
  },
  {
    id: "3",
    projectName: "Mobile attendance MVP",
    client: "Product",
    role: "Designer",
    startDate: "Nov 12, 2025",
    endDate: "Mar 1, 2026",
    status: "completed",
    progress: "100%",
  },
  {
    id: "4",
    projectName: "Employee onboarding flows",
    client: "People Team",
    role: "Contributor",
    startDate: "Dec 1, 2025",
    endDate: "—",
    status: "on-hold",
    progress: "18%",
  },
  {
    id: "5",
    projectName: "Reporting dashboards",
    client: "Analytics",
    role: "Lead",
    startDate: "Mar 20, 2026",
    endDate: "Aug 20, 2026",
    status: "in-progress",
    progress: "12%",
  },
  {
    id: "6",
    projectName: "Leave policy refresh",
    client: "Legal",
    role: "Reviewer",
    startDate: "Oct 5, 2025",
    endDate: "Jan 20, 2026",
    status: "completed",
    progress: "100%",
  },
  {
    id: "7",
    projectName: "Org chart sync",
    client: "IT",
    role: "Contributor",
    startDate: "Jan 15, 2026",
    endDate: "Feb 28, 2026",
    status: "in-progress",
    progress: "55%",
  },
  {
    id: "8",
    projectName: "Benefits enrollment 2026",
    client: "HR Ops",
    role: "Support",
    startDate: "Apr 1, 2026",
    endDate: "May 30, 2026",
    status: "on-hold",
    progress: "5%",
  },
  {
    id: "9",
    projectName: "Security audit checklist",
    client: "Compliance",
    role: "Contributor",
    startDate: "Feb 10, 2026",
    endDate: "Mar 10, 2026",
    status: "completed",
    progress: "100%",
  },
  {
    id: "10",
    projectName: "Training content library",
    client: "L&D",
    role: "Lead",
    startDate: "Mar 1, 2026",
    endDate: "Sep 1, 2026",
    status: "in-progress",
    progress: "28%",
  },
];

function StatusPill({ status }: { status: EmployeeProjectRow["status"] }) {
  if (status === "completed") {
    return (
      <span className="inline-flex items-center gap-1 rounded border border-[#039855] px-2 py-0.5 text-xs font-medium text-[#039855]">
        Completed
        <ChevronDown className="size-3 opacity-80" aria-hidden />
      </span>
    );
  }
  if (status === "on-hold") {
    return (
      <span className="inline-flex items-center gap-1 rounded border border-[#F79009] px-2 py-0.5 text-xs font-medium text-[#B54708]">
        On hold
        <ChevronDown className="size-3 opacity-80" aria-hidden />
      </span>
    );
  }
  return (
    <span className="inline-flex items-center gap-1 rounded border border-[#074473] px-2 py-0.5 text-xs font-medium text-[#074473]">
      In progress
      <ChevronDown className="size-3 opacity-80" aria-hidden />
    </span>
  );
}

const columns: ColumnDef<EmployeeProjectRow>[] = [
  {
    accessorKey: "id",
    header: () => <span className="capitalize">#</span>,
    cell: ({ row }) => (
      <span className="text-[13px] font-medium text-[#272833]">{row.original.id}</span>
    ),
    size: 40,
  },
  {
    accessorKey: "projectName",
    header: () => <span className="capitalize">Project name</span>,
    cell: ({ row }) => (
      <span className="text-[13px] font-medium text-[#272833]">{row.original.projectName}</span>
    ),
  },
  {
    accessorKey: "client",
    header: () => <span className="capitalize">Client / Team</span>,
    cell: ({ row }) => (
      <span className="text-[13px] font-medium text-[#16151C]">{row.original.client}</span>
    ),
  },
  {
    accessorKey: "role",
    header: () => <span className="capitalize">Role</span>,
    cell: ({ row }) => (
      <span className="text-[13px] font-medium text-[#16151C]">{row.original.role}</span>
    ),
  },
  {
    accessorKey: "startDate",
    header: () => <span className="capitalize">Start</span>,
    cell: ({ row }) => (
      <span className="text-[13px] font-medium text-[#16151C]">{row.original.startDate}</span>
    ),
  },
  {
    accessorKey: "endDate",
    header: () => <span className="capitalize">End</span>,
    cell: ({ row }) => (
      <span className="text-[13px] font-medium text-[#16151C]">{row.original.endDate}</span>
    ),
  },
  {
    accessorKey: "progress",
    header: () => <span className="capitalize">Progress</span>,
    cell: ({ row }) => (
      <span className="text-[13px] font-medium text-[#16151C]">{row.original.progress}</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 BlockViewEmployeeProjects = () => {
  const [sorting, setSorting] = useState<SortingState>([]);
  const [globalFilter, setGlobalFilter] = useState("");

  const stats = useMemo(() => {
    const active = STATIC_PROJECTS.filter((p) => p.status === "in-progress").length;
    const done = STATIC_PROJECTS.filter((p) => p.status === "completed").length;
    const hold = STATIC_PROJECTS.filter((p) => p.status === "on-hold").length;
    return { active, done, hold, total: STATIC_PROJECTS.length };
  }, []);

  const table = useReactTable({
    data: STATIC_PROJECTS,
    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.projectName.toLowerCase().includes(q) ||
        r.client.toLowerCase().includes(q) ||
        r.role.toLowerCase().includes(q) ||
        r.status.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]">Projects</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 projects"
              />
            </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="In progress" value={String(stats.active)} />
          <SummaryCard label="Completed" value={String(stats.done)} />
          <SummaryCard label="On hold" value={String(stats.hold)} />
          <SummaryCard label="Total projects" value={String(stats.total)} sub="assigned" />
        </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 projects 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 BlockViewEmployeeProjects;
