"use client";

import { Button } from "@/components/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import type { CandidateRow, CandidateTab } from "@/types/candidate";
import {
  ColumnDef,
  flexRender,
  getCoreRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  RowSelectionState,
  SortingState,
  useReactTable,
} from "@tanstack/react-table";
import { Check } from "lucide-react";
import { useState } from "react";
import CandidatesSearchFilters from "./candidates-search-filters";

const TABS: { id: CandidateTab; label: string }[] = [
  { id: "applied", label: "Applied Candidates" },
  { id: "shortlisted", label: "Shortlisted Candidates" },
  { id: "scheduled", label: "Scheduled Time" },
];

type Props = {
  data: CandidateRow[];
  columns: ColumnDef<CandidateRow>[];
  activeTab: CandidateTab;
  onTabChange: (tab: CandidateTab) => void;
  searchValue: string;
  onSearchChange: (value: string) => void;
  onFiltersClick?: () => void;
};

export default function CandidatesFilledPanel({
  data,
  columns,
  activeTab,
  onTabChange,
  searchValue,
  onSearchChange,
  onFiltersClick,
}: Props) {
  const [sorting, setSorting] = useState<SortingState>([]);
  const [rowSelection, setRowSelection] = useState<RowSelectionState>({});

  const table = useReactTable({
    data,
    columns,
    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="flex flex-col gap-6">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between lg:gap-6">
        <div className="min-w-0 flex-1 border-b border-[#EBEEF2]">
          <nav className="-mb-px flex flex-wrap gap-6" aria-label="Candidate categories">
            {TABS.map((tab) => {
              const isActive = activeTab === tab.id;
              return (
                <button
                  key={tab.id}
                  type="button"
                  onClick={() => onTabChange(tab.id)}
                  className={`relative flex items-center gap-1.5 pb-3 text-sm font-medium transition-colors ${
                    isActive ? "text-[#074473]" : "text-[#858C94] hover:text-[#45464E]"
                  }`}
                >
                  <Check
                    className={`size-4 shrink-0 stroke-[2.5] ${isActive ? "text-[#074473]" : "invisible"}`}
                    aria-hidden
                  />
                  {tab.label}
                  {isActive ? (
                    <span className="absolute bottom-0 left-0 right-0 h-0.5 rounded-full bg-[#074473]" />
                  ) : null}
                </button>
              );
            })}
          </nav>
        </div>
        <CandidatesSearchFilters
          searchValue={searchValue}
          onSearchChange={onSearchChange}
          onFiltersClick={onFiltersClick}
        />
      </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="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 candidates in this tab.
                </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>
  );
}
