// data-table.tsx
"use client";

import * as React from "react";
import { Search, X, CalendarRange, ChevronLeft, ChevronRight, ChevronUp, ChevronDown, ChevronsUpDown, SearchX, SlidersHorizontal, Eye } from "lucide-react";
import {
  ColumnDef,
  FilterFn,
  RowData,
  flexRender,
  getCoreRowModel,
  getSortedRowModel,
  getPaginationRowModel,
  getFilteredRowModel,
  useReactTable,
  SortingState,
  ColumnFiltersState,
  Table as TanstackTable,
} from "@tanstack/react-table";

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { formatNumber, parseNumber } from "@/lib/common";
import type { NumericValue } from "@/lib/common";

// Extend TanStack column meta to support filterVariant
declare module "@tanstack/react-table" {
  interface ColumnMeta<TData extends RowData, TValue> {
    filterVariant?: "dateRange" | "select";
    selectOptions?: { label: string; value: string }[];
  }
}

const DEFAULT_PAGE_SIZE = 15;
const BRAND = "#428B4D";

type DateRangeValue = { from: string; to: string };

const dateToSortableTimestamp = (value: unknown): number | null => {
  if (value instanceof Date) {
    const time = value.getTime();
    return Number.isNaN(time) ? null : time;
  }

  if (typeof value === "number") {
    return Number.isFinite(value) ? value : null;
  }

  if (typeof value !== "string") return null;
  const normalized = value.trim();
  if (!normalized) return null;

  const parsed = new Date(normalized);
  const parsedTime = parsed.getTime();
  if (!Number.isNaN(parsedTime)) return parsedTime;

  return null;
};

const dateSortingFn = (rowA: any, rowB: any, columnId: string) => {
  const a = dateToSortableTimestamp(rowA.getValue(columnId));
  const b = dateToSortableTimestamp(rowB.getValue(columnId));
  if (a === null && b === null) return 0;
  if (a === null) return 1;
  if (b === null) return -1;
  return a - b;
};

const dateRangeFilterFn: FilterFn<any> = (row, columnId, filterValue: DateRangeValue) => {
  const { from, to } = filterValue;
  if (!from && !to) return true;
  const cellValue = row.getValue(columnId) as string;
  if (!cellValue) return true;
  const rowDate = new Date(cellValue);
  if (isNaN(rowDate.getTime())) return true;
  if (from) {
    const fromDate = new Date(from);
    fromDate.setHours(0, 0, 0, 0);
    if (rowDate < fromDate) return false;
  }
  if (to) {
    const toDate = new Date(to);
    toDate.setHours(23, 59, 59, 999);
    if (rowDate > toDate) return false;
  }
  return true;
};
dateRangeFilterFn.autoRemove = (val: DateRangeValue) => !val?.from && !val?.to;

function useFilterVisibility(containerRef: React.RefObject<HTMLDivElement | null>) {
  const [visibleFilters, setVisibleFilters] = React.useState<Record<string, boolean>>({});

  const toggleFilter = React.useCallback((columnId: string) => {
    setVisibleFilters((prev) => {
      const isCurrentlyVisible = !!prev[columnId];
      return {
        ...Object.fromEntries(Object.keys(prev).map((key) => [key, false])),
        [columnId]: !isCurrentlyVisible,
      };
    });
  }, []);

  React.useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as Node;
      if (containerRef.current && containerRef.current.contains(target)) return;
      setVisibleFilters({});
    };
    const handleScroll = () => setVisibleFilters({});

    document.addEventListener("click", handleClickOutside);
    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => {
      document.removeEventListener("click", handleClickOutside);
      window.removeEventListener("scroll", handleScroll);
    };
  }, [containerRef]);

  return { visibleFilters, toggleFilter };
}

/* ── Text filter popup ─────────────────────────────────────────────────── */
function FilterInput({ value, onChange, label }: { value: string; onChange: (v: string) => void; label: string }) {
  return (
    <div
      className="absolute left-0 top-full z-30 mt-2 w-56 overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-2xl ring-1 ring-black/5"
      onClick={(e) => e.stopPropagation()}
    >
      {/* Header */}
      <div className="flex items-center gap-2 border-b border-slate-100 bg-slate-50/80 px-3 py-2">
        <SlidersHorizontal className="h-3.5 w-3.5 shrink-0" style={{ color: BRAND }} />
        <span className="text-[10px] font-bold uppercase tracking-widest text-slate-500">{label}</span>
        {value && (
          <button
            type="button"
            onClick={(e) => { e.stopPropagation(); onChange(""); }}
            className="ml-auto rounded-md p-0.5 text-slate-400 transition-colors hover:bg-red-50 hover:text-red-500"
          >
            <X className="h-3 w-3" />
          </button>
        )}
      </div>

      {/* Input */}
      <div className="p-3">
        <div className="relative">
          <Search className="absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-400" />
          <input
            autoFocus
            type="text"
            value={value}
            onClick={(e) => e.stopPropagation()}
            onChange={(e) => onChange(e.target.value)}
            placeholder="Type to filter…"
            className="w-full rounded-xl border border-slate-200 bg-slate-50 py-2 pl-8 pr-3 text-xs text-slate-700 placeholder:text-slate-400 transition-all focus:border-transparent focus:bg-white focus:outline-none focus:ring-2"
            style={{ focusRingColor: BRAND } as React.CSSProperties}
            onFocus={(e) => { e.currentTarget.style.boxShadow = `0 0 0 2px ${BRAND}40`; e.currentTarget.style.borderColor = BRAND; }}
            onBlur={(e) => { e.currentTarget.style.boxShadow = ""; e.currentTarget.style.borderColor = ""; }}
          />
        </div>
        {value && (
          <p className="mt-1.5 text-[10px] text-slate-400">
            Filtering by <span className="font-semibold text-slate-600">&ldquo;{value}&rdquo;</span>
          </p>
        )}
      </div>
    </div>
  );
}
function SelectFilterInput({ value, onChange, label, options }: {
  value: string[];
  onChange: (v: string[]) => void;
  label: string;
  options: { label: string; value: string }[];
}) {
  const [search, setSearch] = React.useState("");
  const selected = Array.isArray(value) ? value : value ? [value] : [];

  const filtered = options.filter((o) =>
    o.label.toLowerCase().includes(search.toLowerCase())
  );

  const toggle = (val: string) => {
    if (selected.includes(val)) {
      onChange(selected.filter((v) => v !== val));
    } else {
      onChange([...selected, val]);
    }
  };

  return (
    <div
      className="absolute left-0 top-full z-30 mt-2 w-56 overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-2xl ring-1 ring-black/5"
      onClick={(e) => e.stopPropagation()}
    >
      {/* Header */}
      <div className="flex items-center gap-2 border-b border-slate-100 bg-slate-50/80 px-3 py-2">
        <SlidersHorizontal className="h-3.5 w-3.5 shrink-0" style={{ color: BRAND }} />
        <span className="text-[10px] font-bold uppercase tracking-widest text-slate-500">{label}</span>
        {selected.length > 0 && (
          <button
            type="button"
            onClick={(e) => { e.stopPropagation(); onChange([]); setSearch(""); }}
            className="ml-auto rounded-md p-0.5 text-slate-400 transition-colors hover:bg-red-50 hover:text-red-500"
          >
            <X className="h-3 w-3" />
          </button>
        )}
      </div>

      {/* Search */}
      <div className="p-2 border-b border-slate-100">
        <div className="relative">
          <Search className="absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-400" />
          <input
            autoFocus
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            onClick={(e) => e.stopPropagation()}
            placeholder="Search..."
            className="w-full rounded-xl border border-slate-200 bg-slate-50 py-1.5 pl-8 pr-3 text-xs text-slate-700 placeholder:text-slate-400 focus:outline-none focus:border-transparent focus:ring-2"
            onFocus={(e) => { e.currentTarget.style.boxShadow = `0 0 0 2px ${BRAND}40`; e.currentTarget.style.borderColor = BRAND; }}
            onBlur={(e) => { e.currentTarget.style.boxShadow = ""; e.currentTarget.style.borderColor = ""; }}
          />
        </div>
      </div>

      {/* Options */}
      <div className="max-h-48 overflow-y-auto p-1.5">
        {filtered.length === 0 ? (
          <p className="px-3 py-2 text-xs text-slate-400">No results</p>
        ) : (
          filtered.map((opt) => {
            const isChecked = selected.includes(opt.value);
            return (
              <button
                key={opt.value}
                type="button"
                onClick={(e) => { e.stopPropagation(); toggle(opt.value); }}
                className="flex w-full items-center gap-2 rounded-lg px-3 py-1.5 text-left text-xs transition-colors hover:bg-slate-50"
              >
                <span
                  className="flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded border transition-colors"
                  style={isChecked ? { backgroundColor: BRAND, borderColor: BRAND } : { borderColor: "#cbd5e1" }}
                >
                  {isChecked && (
                    <svg viewBox="0 0 10 10" className="h-2.5 w-2.5 text-white" fill="none" stroke="currentColor" strokeWidth="2">
                      <path d="M1.5 5l2.5 2.5 4.5-4.5" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                  )}
                </span>
                <span className={`truncate ${isChecked ? "font-semibold text-slate-800" : "text-slate-700"}`}>
                  {opt.label}
                </span>
              </button>
            );
          })
        )}
      </div>

      {/* Selected count badge */}
      {selected.length > 0 && (
        <div className="border-t border-slate-100 px-3 py-1.5">
          <span className="text-[10px] font-semibold" style={{ color: BRAND }}>
            {selected.length} selected
          </span>
        </div>
      )}
    </div>
  );
}
/* ── Date-range filter popup ───────────────────────────────────────────── */
function DateRangeFilterInput({
  value,
  onChange,
  label,
}: {
  value: DateRangeValue;
  onChange: (v: DateRangeValue) => void;
  label: string;
}) {
  const hasValue = value.from || value.to;

  const fmt = (d: string) =>
    d ? new Date(d).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }) : null;

  return (
    <div
      className="absolute left-0 top-full z-30 mt-2 w-72 overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-2xl ring-1 ring-black/5"
      onClick={(e) => e.stopPropagation()}
    >
      {/* Header */}
      <div className="flex items-center gap-2 border-b border-slate-100 bg-slate-50/80 px-3 py-2">
        <CalendarRange className="h-3.5 w-3.5 shrink-0" style={{ color: BRAND }} />
        <span className="text-[10px] font-bold uppercase tracking-widest text-slate-500">{label}</span>
        {hasValue && (
          <button
            type="button"
            onClick={(e) => { e.stopPropagation(); onChange({ from: "", to: "" }); }}
            className="ml-auto rounded-md p-0.5 text-slate-400 transition-colors hover:bg-red-50 hover:text-red-500"
          >
            <X className="h-3 w-3" />
          </button>
        )}
      </div>

      {/* Active range badge */}
      {hasValue && (
        <div className="mx-3 mt-3 flex items-center gap-1.5 rounded-xl px-3 py-1.5 text-[11px] font-semibold text-white"
          style={{ background: `linear-gradient(135deg, ${BRAND}, #5aad6a)` }}>
          <CalendarRange className="h-3 w-3 shrink-0" />
          <span className="truncate">
            {fmt(value.from) ?? "Any"} → {fmt(value.to) ?? "Any"}
          </span>
        </div>
      )}

      {/* Date inputs */}
      <div className="space-y-3 p-3">
        <div>
          <label className="mb-1.5 flex items-center gap-1.5 text-[10px] font-bold uppercase tracking-widest text-slate-500">
            <span className="inline-flex h-4 w-4 items-center justify-center rounded-full text-[9px] font-black text-white" style={{ backgroundColor: BRAND }}>F</span>
            From
          </label>
          <input
            autoFocus
            type="date"
            value={value.from}
            max={value.to || undefined}
            onClick={(e) => e.stopPropagation()}
            onChange={(e) => onChange({ ...value, from: e.target.value })}
            className="w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-xs text-slate-700 transition-all focus:bg-white focus:outline-none"
            style={{ colorScheme: "light" }}
            onFocus={(e) => { e.currentTarget.style.boxShadow = `0 0 0 2px ${BRAND}40`; e.currentTarget.style.borderColor = BRAND; }}
            onBlur={(e) => { e.currentTarget.style.boxShadow = ""; e.currentTarget.style.borderColor = ""; }}
          />
        </div>

        <div className="flex items-center gap-2">
          <div className="h-px flex-1 bg-slate-100" />
          <span className="text-[9px] font-bold uppercase tracking-widest text-slate-400">to</span>
          <div className="h-px flex-1 bg-slate-100" />
        </div>

        <div>
          <label className="mb-1.5 flex items-center gap-1.5 text-[10px] font-bold uppercase tracking-widest text-slate-500">
            <span className="inline-flex h-4 w-4 items-center justify-center rounded-full text-[9px] font-black text-white" style={{ backgroundColor: BRAND }}>T</span>
            To
          </label>
          <input
            type="date"
            value={value.to}
            min={value.from || undefined}
            onClick={(e) => e.stopPropagation()}
            onChange={(e) => onChange({ ...value, to: e.target.value })}
            className="w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-xs text-slate-700 transition-all focus:bg-white focus:outline-none"
            style={{ colorScheme: "light" }}
            onFocus={(e) => { e.currentTarget.style.boxShadow = `0 0 0 2px ${BRAND}40`; e.currentTarget.style.borderColor = BRAND; }}
            onBlur={(e) => { e.currentTarget.style.boxShadow = ""; e.currentTarget.style.borderColor = ""; }}
          />
        </div>
      </div>
    </div>
  );
}

/* ── Pagination ────────────────────────────────────────────────────────── */
interface PaginationProps<TData> {
  table: TanstackTable<TData>;
  totalRows: number;
}

function Pagination<TData>({ table, totalRows }: PaginationProps<TData>) {
  const { pageIndex, pageSize } = table.getState().pagination;
  const filteredCount = table.getFilteredRowModel().rows.length;
  const from = pageIndex * pageSize + 1;
  const to = Math.min((pageIndex + 1) * pageSize, filteredCount);
  const pageCount = table.getPageCount();

  return (
    <div className="flex items-center justify-between gap-3 px-1">
      <p className="text-[11px] text-slate-400 tabular-nums">
        {filteredCount > 0 ? (
          <>
            <span className="font-semibold text-slate-600">{from}–{to}</span>
            {" "}of{" "}
            <span className="font-semibold text-slate-600">{filteredCount}</span>
            {filteredCount !== totalRows && (
              <span className="text-slate-400"> (filtered from {totalRows})</span>
            )}
          </>
        ) : (
          "No results"
        )}
      </p>
      <div className="flex items-center gap-1.5">
        <button
          onClick={() => table.previousPage()}
          disabled={!table.getCanPreviousPage()}
          className="inline-flex h-7 w-7 items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-500 shadow-sm transition-all hover:border-[#428B4D]/40 hover:text-[#428B4D] disabled:cursor-not-allowed disabled:opacity-40"
          aria-label="Previous page"
        >
          <ChevronLeft className="h-3.5 w-3.5" />
        </button>
        <span className="text-[11px] font-semibold tabular-nums text-slate-500">
          {pageIndex + 1} / {Math.max(pageCount, 1)}
        </span>
        <button
          onClick={() => table.nextPage()}
          disabled={!table.getCanNextPage()}
          className="inline-flex h-7 w-7 items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-500 shadow-sm transition-all hover:border-[#428B4D]/40 hover:text-[#428B4D] disabled:cursor-not-allowed disabled:opacity-40"
          aria-label="Next page"
        >
          <ChevronRight className="h-3.5 w-3.5" />
        </button>
      </div>
    </div>
  );
}

/* ── DataTable ─────────────────────────────────────────────────────────── */
interface DataTableProps<TData> {
  columns: ColumnDef<TData, any>[];
  data: TData[];
  pageSize?: number;
  onFilteredDataChange?: (rows: TData[]) => void;
  summaryConfig?: {
    quantityKey: string;
    amountKey: string;
    currencyKey?: string;
    quantityUniqueByKey?: string;
    quantityUniqueByKeys?: string[];
    customQuantityTotal?: (rows: TData[]) => number;
    onView?: () => void;
  };
}

export function DataTable<TData>({
  columns,
  data,
  pageSize = DEFAULT_PAGE_SIZE,
  onFilteredDataChange,
  summaryConfig,
}: DataTableProps<TData>) {
  const [sorting, setSorting] = React.useState<SortingState>([]);
  const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([]);
  const containerRef = React.useRef<HTMLDivElement | null>(null);
  const { visibleFilters, toggleFilter } = useFilterVisibility(containerRef);
  const normalizedColumns = React.useMemo(() => {
    const applyDateSorting = (defs: ColumnDef<TData, any>[]): ColumnDef<TData, any>[] =>
      defs.map((col) => {
        const nextCol: ColumnDef<TData, any> = { ...col };

        if ("columns" in nextCol && Array.isArray(nextCol.columns)) {
          nextCol.columns = applyDateSorting(nextCol.columns as ColumnDef<TData, any>[]);
        }

        const isDateRange = nextCol.meta?.filterVariant === "dateRange";
        if (isDateRange && !nextCol.sortingFn) {
          nextCol.sortingFn = dateSortingFn;
          nextCol.sortUndefined = "last";
        }

        return nextCol;
      });

    return applyDateSorting(columns);
  }, [columns]);

  const table = useReactTable({
    data,
    columns: normalizedColumns,
    state: { sorting, columnFilters },
    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    filterFns: { dateRange: dateRangeFilterFn },
    initialState: { pagination: { pageSize } },
  });

  const rows = table.getRowModel().rows;
  const filteredRows = table.getFilteredRowModel().rows;
  const activeFilterCount = columnFilters.length;

  React.useEffect(() => {
    if (!onFilteredDataChange) return;
    onFilteredDataChange(filteredRows.map((row) => row.original));
  }, [filteredRows, onFilteredDataChange]);
  const filteredSummary = React.useMemo(() => {
    if (!summaryConfig) return null;

    const quantityTotal = summaryConfig.customQuantityTotal
      ? summaryConfig.customQuantityTotal(filteredRows.map((row) => row.original))
      : (summaryConfig.quantityUniqueByKey || summaryConfig.quantityUniqueByKeys?.length)
      ? (() => {
          const quantityByGroup = new Map<string, number>();
          const uniqueKeys = summaryConfig.quantityUniqueByKeys?.length
            ? summaryConfig.quantityUniqueByKeys
            : summaryConfig.quantityUniqueByKey
            ? [summaryConfig.quantityUniqueByKey]
            : [];

          for (const row of filteredRows) {
            const source = row.original as Record<string, unknown>;
            const groupKey = uniqueKeys
              .map((key) => String(source[key] ?? "").trim())
              .find(Boolean) || "";
            if (!groupKey) continue;
            const quantityValue = source[summaryConfig.quantityKey];
            const quantity = parseNumber(
              (typeof quantityValue === "number" ||
                typeof quantityValue === "string" ||
                quantityValue === null ||
                quantityValue === undefined
                ? quantityValue
                : 0) as NumericValue
            );
            const existing = quantityByGroup.get(groupKey);
            if (existing === undefined || Math.abs(quantity) > Math.abs(existing)) {
              quantityByGroup.set(groupKey, quantity);
            }
          }
          return Array.from(quantityByGroup.values()).reduce((sum, quantity) => sum + quantity, 0);
        })()
      : filteredRows.reduce((sum, row) => {
          const source = row.original as Record<string, unknown>;
          const quantityValue = source[summaryConfig.quantityKey];
          const quantity = parseNumber(
            (typeof quantityValue === "number" ||
              typeof quantityValue === "string" ||
              quantityValue === null ||
              quantityValue === undefined
              ? quantityValue
              : 0) as NumericValue
          );
          return sum + quantity;
        }, 0);

    const amountTotal = filteredRows.reduce((sum, row) => {
      const source = row.original as Record<string, unknown>;
      const amountValue = source[summaryConfig.amountKey];
      const amount = parseNumber(
        (typeof amountValue === "number" ||
          typeof amountValue === "string" ||
          amountValue === null ||
          amountValue === undefined
          ? amountValue
          : 0) as NumericValue
      );
      return sum + amount;
    }, 0);

    const currencyKey = summaryConfig.currencyKey;
    const currency = currencyKey
      ? filteredRows.find((row) => {
          const source = row.original as Record<string, unknown>;
          return !!source[currencyKey];
        })?.original
      : null;

    const currencyCode =
      currencyKey && currency
        ? String((currency as Record<string, unknown>)[currencyKey] ?? "").trim()
        : "";

    return {
      quantity: formatNumber(quantityTotal),
      amount: formatNumber(amountTotal),
      currencyCode,
    };
  }, [filteredRows, summaryConfig]);

  return (
    <div ref={containerRef} className="flex flex-col gap-3">

      {/* Active filter pills */}
      {activeFilterCount > 0 && (
        <div className="flex flex-wrap items-center gap-2">
          <span className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Active filters:</span>
          {columnFilters.map((f) => {
            const isDR = typeof f.value === "object" && f.value !== null && "from" in f.value;
            const dr = f.value as DateRangeValue;
            const fmt = (d: string) =>
              d ? new Date(d).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }) : "";
            const label = isDR
              ? `${fmt(dr.from) || "Any"} → ${fmt(dr.to) || "Any"}`
              : String(f.value);
            return (
              <span
                key={f.id}
                className="inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-[10px] font-semibold"
                style={{ borderColor: `${BRAND}40`, backgroundColor: `${BRAND}0d`, color: BRAND }}
              >
                <span className="capitalize">{f.id.replace(/_/g, " ")}:</span>
                <span className="font-bold">{label}</span>
                <button
                  type="button"
                  onClick={() => table.getColumn(f.id)?.setFilterValue(undefined)}
                  className="ml-0.5 rounded-full p-0.5 opacity-60 transition-opacity hover:opacity-100"
                >
                  <X className="h-2.5 w-2.5" />
                </button>
              </span>
            );
          })}
          <button
            type="button"
            onClick={() => table.resetColumnFilters()}
            className="ml-1 rounded-full border border-red-200 bg-red-50 px-2.5 py-0.5 text-[10px] font-bold text-red-500 transition-colors hover:bg-red-100"
          >
            Clear all
          </button>
        </div>
      )}

      {/* Table */}
      <div className="overflow-hidden rounded-2xl border border-slate-200/80 bg-white shadow-sm">
        <div className="overflow-x-auto">
          <Table className="min-w-full text-sm">
            <TableHeader>
              {table.getHeaderGroups().map((headerGroup) => (
                <TableRow key={headerGroup.id} className="border-b border-slate-100 bg-slate-50/70 hover:bg-slate-50/70">
                  {headerGroup.headers.map((header) => {
                    const columnId = header.column.id;
                    const showFilter = visibleFilters[columnId];
                    const filterVariant = header.column.columnDef.meta?.filterVariant;
                    const isDateRange = filterVariant === "dateRange";
                    const isSelect = filterVariant === "select";
                    const filterValue = header.column.getFilterValue();
                    const isFiltered = isDateRange
                      ? Boolean((filterValue as DateRangeValue)?.from || (filterValue as DateRangeValue)?.to)
                      : isSelect
                      ? Array.isArray(filterValue) ? filterValue.length > 0 : !!filterValue
                      : !!filterValue;
                    const headerLabel =
                      typeof header.column.columnDef.header === "string"
                        ? header.column.columnDef.header
                        : columnId;

                    return (
                      <TableHead
                        key={header.id}
                        className="px-4 py-3 text-left select-none"
                      >
                        {header.isPlaceholder ? null : (
                          <div className="relative flex items-center gap-1.5">
                            {/* Sort trigger — clicking label area */}
                            <button
                              type="button"
                              onClick={() => header.column.getCanSort() && header.column.toggleSorting()}
                              className={`group flex min-w-0 items-center gap-1 transition-colors ${
                                header.column.getCanSort() ? "cursor-pointer" : "cursor-default"
                              }`}
                            >
                              <span className={`truncate text-[10px] font-semibold uppercase tracking-widest transition-colors ${
                                header.column.getIsSorted() ? "text-[#428B4D]" : "text-slate-500 group-hover:text-slate-700"
                              }`}>
                                {flexRender(header.column.columnDef.header, header.getContext())}
                              </span>
                              {header.column.getCanSort() && (
                                <span className="shrink-0">
                                  {header.column.getIsSorted() === "asc" ? (
                                    <ChevronUp className="h-3 w-3 text-[#428B4D]" />
                                  ) : header.column.getIsSorted() === "desc" ? (
                                    <ChevronDown className="h-3 w-3 text-[#428B4D]" />
                                  ) : (
                                    <ChevronsUpDown className="h-3 w-3 text-slate-300 group-hover:text-slate-400" />
                                  )}
                                </span>
                              )}
                            </button>

                            {header.column.getCanFilter() && (
                              <button
                                type="button"
                                onClick={(e) => { e.stopPropagation(); toggleFilter(columnId); }}
                                className={`group relative inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-md transition-all ${
                                  isFiltered
                                    ? "text-white shadow-sm"
                                    : showFilter
                                    ? "bg-slate-100 text-slate-600"
                                    : "text-slate-300 hover:bg-slate-100 hover:text-slate-500"
                                }`}
                                style={isFiltered ? { backgroundColor: BRAND } : {}}
                                title={`Filter by ${headerLabel}`}
                              >
                                <SlidersHorizontal className="h-2.5 w-2.5" />
                                {isFiltered && (
                                  <span className="absolute -right-0.5 -top-0.5 h-1.5 w-1.5 rounded-full bg-emerald-300 ring-1 ring-white" />
                                )}
                              </button>
                            )}

                            {header.column.getCanFilter() && showFilter && (
                              isDateRange ? (
                                <DateRangeFilterInput
                                  label={headerLabel}
                                  value={(filterValue ?? { from: "", to: "" }) as DateRangeValue}
                                  onChange={(val) => header.column.setFilterValue(val)}
                                />
                              ) : isSelect ? (
                                <SelectFilterInput
                                  label={headerLabel}
                                  value={(filterValue ?? []) as string[]}
                                  onChange={(val) => header.column.setFilterValue(val.length ? val : undefined)}
                                  options={header.column.columnDef.meta?.selectOptions ?? []}
                                />
                              ) : (
                                <FilterInput
                                  label={headerLabel}
                                  value={(filterValue ?? "") as string}
                                  onChange={(val) => header.column.setFilterValue(val)}
                                />
                              )
                            )}
                          </div>
                        )}
                      </TableHead>
                    );
                  })}
                </TableRow>
              ))}
            </TableHeader>

            <TableBody>
              {rows.length > 0 ? (
                rows.map((row, rowIndex) => (
                  <TableRow
                    key={row.id}
                    className={`border-b border-slate-50 transition-colors last:border-0 ${
                      rowIndex % 2 === 0 ? "bg-white" : "bg-slate-50/40"
                    } hover:bg-[#428B4D]/5`}
                  >
                    {row.getVisibleCells().map((cell) => (
                      <TableCell key={cell.id} className="px-4 py-2.5 text-xs text-slate-700">
                        {flexRender(cell.column.columnDef.cell, cell.getContext())}
                      </TableCell>
                    ))}
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={columns.length} className="h-40 text-center">
                    <div className="flex flex-col items-center justify-center gap-2 text-slate-400">
                      <SearchX className="h-8 w-8 opacity-40" />
                      <p className="text-sm font-medium">No results found</p>
                      <p className="text-xs">Try adjusting your filters</p>
                    </div>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>
      </div>

      {/* Pagination */}
      <Pagination table={table} totalRows={data.length} />

      {filteredSummary && activeFilterCount > 0 && (
        <div className="flex justify-end">
          <div className="overflow-hidden rounded-md border border-slate-200 bg-slate-50 shadow-sm">
            <div className={`grid text-xs ${summaryConfig?.onView ? "grid-cols-[auto_auto_auto_auto_auto]" : "grid-cols-4"}`}>
              <div className="border-r border-slate-200 px-4 py-2 font-semibold text-slate-700">
                Total Quantity
              </div>
              <div className="border-r border-slate-200 px-4 py-2 text-slate-700">
                {filteredSummary.quantity}
              </div>
              <div className="border-r border-slate-200 px-4 py-2 font-semibold text-slate-700">
                Total Amount
              </div>
              <div className="px-4 py-2 text-slate-700">
                {filteredSummary.currencyCode ? `${filteredSummary.currencyCode} ` : ""}
                {filteredSummary.amount}
              </div>
              {summaryConfig?.onView && (
                <button
                  type="button"
                  onClick={summaryConfig.onView}
                  className="inline-flex items-center justify-center border-l border-slate-200 px-3 py-2 text-[#16a3be] transition-colors hover:bg-slate-100"
                  title="View details"
                  aria-label="View details"
                >
                  <Eye className="h-4 w-4" />
                </button>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
