import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { ChevronLeft, ChevronRight, Loader2 } from "lucide-react";
import type { ReactNode } from "react";
import { EmptyState, ErrorState, TableSkeleton, UpdatingBar } from "./states";
import { Button } from "@/components/ui/button";
import type { Page } from "@/api/types";
import { fmtInt } from "@/lib/format";
import { cn } from "@/lib/utils";

export interface Column<T> {
  key: string;
  header: string;
  cell: (row: T) => ReactNode;
  align?: "right" | "left";
  className?: string;
  sortKey?: string;
}

/** Server-side table: pagination, skeleton, dimmed refetch, empty vs no-results states. */
export function DataTable<T>({
  queryKey,
  fetcher,
  columns,
  page,
  pageSize = 25,
  onPage,
  onRowClick,
  rowKey,
  empty,
  filtered = false,
  onClearFilters,
  sort,
  onSort,
}: {
  queryKey: unknown[];
  fetcher: () => Promise<Page<T>>;
  columns: Column<T>[];
  page: number;
  pageSize?: number;
  onPage: (p: number) => void;
  onRowClick?: (row: T) => void;
  rowKey: (row: T) => string;
  empty: { title: string; text: string; action?: ReactNode };
  filtered?: boolean;
  onClearFilters?: () => void;
  sort?: string;
  onSort?: (s: string) => void;
}) {
  const q = useQuery({ queryKey, queryFn: fetcher, placeholderData: keepPreviousData });
  if (q.isPending) return <TableSkeleton cols={Math.min(columns.length, 8)} />;
  if (q.isError) return <ErrorState error={q.error} onRetry={() => void q.refetch()} />;
  const data = q.data;
  const pages = Math.max(1, Math.ceil(data.total / pageSize));
  return (
    <div className="relative overflow-hidden rounded-xl border bg-card">
      <UpdatingBar active={q.isPlaceholderData || q.isFetching} />
      <div className="overflow-x-auto">
        <table className="w-full text-left text-[13.5px] tabular">
          <thead className="sticky top-0 bg-surface-2 text-[12.5px] text-muted-foreground">
            <tr>
              {columns.map((c) => (
                <th
                  key={c.key}
                  scope="col"
                  className={cn(
                    "whitespace-nowrap px-4 py-2.5 font-semibold",
                    c.align === "right" && "text-right",
                  )}
                >
                  {c.sortKey && onSort ? (
                    <button
                      type="button"
                      className="hover:text-foreground"
                      onClick={() =>
                        onSort(
                          sort === `${c.sortKey}:asc` ? `${c.sortKey}:desc` : `${c.sortKey}:asc`,
                        )
                      }
                    >
                      {c.header}
                      {sort?.startsWith(`${c.sortKey}:`)
                        ? sort.endsWith("asc")
                          ? " ↑"
                          : " ↓"
                        : ""}
                    </button>
                  ) : (
                    c.header
                  )}
                </th>
              ))}
              {q.isPlaceholderData && (
                <th className="w-6">
                  <Loader2 className="h-4 w-4 animate-spin" />
                </th>
              )}
            </tr>
          </thead>
          <tbody className={cn("transition-opacity", q.isPlaceholderData && "opacity-60")}>
            {data.items.map((row) => (
              <tr
                key={rowKey(row)}
                onClick={onRowClick ? () => onRowClick(row) : undefined}
                className={cn(
                  "border-t transition-colors hover:bg-surface-3/60",
                  onRowClick && "cursor-pointer",
                )}
              >
                {columns.map((c) => (
                  <td
                    key={c.key}
                    className={cn(
                      "px-4 py-2.5 align-middle",
                      c.align === "right" && "text-right",
                      c.className,
                    )}
                  >
                    {c.cell(row)}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {data.items.length === 0 &&
        (filtered ? (
          <EmptyState
            title="No results"
            text="Nothing matches these filters."
            action={
              onClearFilters && (
                <Button variant="outline" onClick={onClearFilters}>
                  Clear filters
                </Button>
              )
            }
          />
        ) : (
          <EmptyState title={empty.title} text={empty.text} action={empty.action} />
        ))}
      {data.total > 0 && (
        <div className="flex items-center justify-between gap-3 border-t px-4 py-2.5 text-[12.5px] text-muted-foreground">
          <span>
            {fmtInt((page - 1) * pageSize + 1)}–{fmtInt(Math.min(page * pageSize, data.total))} of{" "}
            {fmtInt(data.total)}
          </span>
          <div className="flex items-center gap-1">
            <Button
              variant="ghost"
              size="sm"
              disabled={page <= 1}
              onClick={() => onPage(page - 1)}
              aria-label="Previous page"
            >
              <ChevronLeft />
            </Button>
            <span>
              Page {page} of {pages}
            </span>
            <Button
              variant="ghost"
              size="sm"
              disabled={page >= pages}
              onClick={() => onPage(page + 1)}
              aria-label="Next page"
            >
              <ChevronRight />
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
