import { useMemo, useState, type ReactNode } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Search } from "lucide-react";

export interface Column<T> {
  key: string;
  header: string;
  cell: (row: T) => ReactNode;
  className?: string;
}

export function AdminDataTable<T extends { id: string }>({
  rows, columns, search, onSearchChange, filters, actions, rowActions, pageSize = 10, empty = "No records",
}: {
  rows: T[];
  columns: Column<T>[];
  search?: string;
  onSearchChange?: (v: string) => void;
  filters?: ReactNode;
  actions?: ReactNode;
  rowActions?: (row: T) => ReactNode;
  pageSize?: number;
  empty?: string;
}) {
  const [page, setPage] = useState(1);
  const totalPages = Math.max(1, Math.ceil(rows.length / pageSize));
  const paged = useMemo(() => rows.slice((page - 1) * pageSize, page * pageSize), [rows, page, pageSize]);

  return (
    <div className="space-y-3">
      <div className="flex flex-wrap items-center gap-2">
        {onSearchChange && (
          <div className="relative min-w-[220px] flex-1">
            <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input placeholder="Search…" value={search ?? ""} onChange={(e) => { onSearchChange(e.target.value); setPage(1); }} className="pl-9" />
          </div>
        )}
        {filters}
        <div className="ml-auto flex items-center gap-2">{actions}</div>
      </div>
      <div className="overflow-hidden rounded-xl border border-border bg-card">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-surface text-left text-xs uppercase text-muted-foreground">
              <tr>
                {columns.map((c) => <th key={c.key} className={`px-3 py-2.5 ${c.className ?? ""}`}>{c.header}</th>)}
                {rowActions && <th className="px-3 py-2.5 text-right">Actions</th>}
              </tr>
            </thead>
            <tbody>
              {paged.length === 0 && (
                <tr><td colSpan={columns.length + (rowActions ? 1 : 0)} className="px-3 py-10 text-center text-muted-foreground">{empty}</td></tr>
              )}
              {paged.map((r) => (
                <tr key={r.id} className="border-t border-border/60 hover:bg-surface/40">
                  {columns.map((c) => <td key={c.key} className={`px-3 py-2.5 ${c.className ?? ""}`}>{c.cell(r)}</td>)}
                  {rowActions && <td className="px-3 py-2.5 text-right">{rowActions(r)}</td>}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
      {totalPages > 1 && (
        <div className="flex items-center justify-between text-xs text-muted-foreground">
          <div>{rows.length} records</div>
          <div className="flex items-center gap-2">
            <Button size="sm" variant="outline" disabled={page === 1} onClick={() => setPage((p) => p - 1)}>Prev</Button>
            <span>Page {page} / {totalPages}</span>
            <Button size="sm" variant="outline" disabled={page === totalPages} onClick={() => setPage((p) => p + 1)}>Next</Button>
          </div>
        </div>
      )}
    </div>
  );
}