import { useState, useMemo } from "react";

interface Column {
  key: string;
  label: string;
  format?: (v: unknown) => string;
}

interface Props {
  columns: Column[];
  data: readonly Record<string, unknown>[] | readonly object[];
  pageSize?: number;
}

export function DataTable({ columns, data: rawData, pageSize = 20 }: Props) {
  const data = rawData as Record<string, unknown>[];
  const [sortKey, setSortKey] = useState<string | null>(null);
  const [sortAsc, setSortAsc] = useState(true);
  const [page, setPage] = useState(0);
  const [filter, setFilter] = useState("");
  const [visibleCols, setVisibleCols] = useState<Set<string>>(
    () => new Set(columns.map((c) => c.key))
  );
  const [showColPicker, setShowColPicker] = useState(false);

  const filtered = useMemo(() => {
    if (!filter) return data;
    const lower = filter.toLowerCase();
    return data.filter((row) =>
      Object.values(row).some((v) =>
        String(v ?? "").toLowerCase().includes(lower)
      )
    );
  }, [data, filter]);

  const sorted = useMemo(() => {
    if (!sortKey) return filtered;
    return [...filtered].sort((a, b) => {
      const va = a[sortKey] ?? "";
      const vb = b[sortKey] ?? "";
      if (typeof va === "number" && typeof vb === "number")
        return sortAsc ? va - vb : vb - va;
      return sortAsc
        ? String(va).localeCompare(String(vb))
        : String(vb).localeCompare(String(va));
    });
  }, [filtered, sortKey, sortAsc]);

  const totalPages = Math.ceil(sorted.length / pageSize);
  const paged = sorted.slice(page * pageSize, (page + 1) * pageSize);
  const shownCols = columns.filter((c) => visibleCols.has(c.key));

  const handleSort = (key: string) => {
    if (sortKey === key) setSortAsc(!sortAsc);
    else {
      setSortKey(key);
      setSortAsc(true);
    }
  };

  const toggleCol = (key: string) => {
    const next = new Set(visibleCols);
    if (next.has(key)) next.delete(key);
    else next.add(key);
    setVisibleCols(next);
  };

  return (
    <div>
      <div className="flex gap-2 mb-4 items-center">
        <div className="relative">
          <svg
            className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-slate-400"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <circle cx="11" cy="11" r="8" />
            <path d="m21 21-4.35-4.35" />
          </svg>
          <input
            type="text"
            placeholder="Search..."
            value={filter}
            onChange={(e) => {
              setFilter(e.target.value);
              setPage(0);
            }}
            className="pl-9 pr-3 py-2 text-xs border border-slate-200 rounded-lg bg-[#f8f7f4] focus:outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-300 w-56 transition-all"
          />
        </div>
        <button
          onClick={() => setShowColPicker(!showColPicker)}
          className={`px-3 py-2 text-xs font-medium border rounded-lg transition-all ${
            showColPicker
              ? "border-indigo-300 bg-indigo-50 text-indigo-600"
              : "border-slate-200 bg-white text-slate-600 hover:bg-slate-50"
          }`}
        >
          Columns
        </button>
        <span className="text-[11px] text-slate-400 ml-auto font-medium">
          {sorted.length} rows
        </span>
      </div>

      {showColPicker && (
        <div className="flex flex-wrap gap-1.5 mb-4 p-3 bg-[#f8f7f4] rounded-xl">
          {columns.map((c) => (
            <label
              key={c.key}
              className={`flex items-center gap-1.5 text-[11px] font-medium px-2.5 py-1.5 rounded-lg cursor-pointer transition-all ${
                visibleCols.has(c.key)
                  ? "bg-indigo-50 text-indigo-700 border border-indigo-200"
                  : "bg-white text-slate-400 border border-slate-200"
              }`}
            >
              <input
                type="checkbox"
                checked={visibleCols.has(c.key)}
                onChange={() => toggleCol(c.key)}
                className="sr-only"
              />
              {c.label}
            </label>
          ))}
        </div>
      )}

      <div className="overflow-x-auto rounded-xl border border-slate-200">
        <table className="w-full text-[12px]">
          <thead>
            <tr className="bg-slate-50/80 sticky top-0">
              {shownCols.map((col) => (
                <th
                  key={col.key}
                  onClick={() => handleSort(col.key)}
                  className="px-3 py-2.5 text-left text-[10px] font-bold text-slate-400 uppercase tracking-wider cursor-pointer hover:text-slate-600 whitespace-nowrap transition-colors border-b border-slate-200"
                >
                  {col.label}
                  {sortKey === col.key && (
                    <span className="text-indigo-500 ml-1">
                      {sortAsc ? "\u2191" : "\u2193"}
                    </span>
                  )}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {paged.map((row, i) => (
              <tr key={i} className={`${i % 2 === 0 ? "bg-white" : "bg-slate-50/40"} hover:bg-indigo-50/30 transition-colors`}>
                {shownCols.map((col) => (
                  <td
                    key={col.key}
                    className="px-3 py-2 whitespace-nowrap text-slate-600 font-mono"
                  >
                    {col.format
                      ? col.format(row[col.key])
                      : String(row[col.key] ?? "\u2014")}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {totalPages > 1 && (
        <div className="flex items-center justify-between mt-4">
          <p className="text-[11px] text-slate-400 font-medium">
            Page {page + 1} of {totalPages}
          </p>
          <div className="flex gap-1">
            <button
              disabled={page === 0}
              onClick={() => setPage(page - 1)}
              className="px-3 py-1.5 text-xs font-medium rounded-lg border border-slate-200 bg-white hover:bg-slate-50 disabled:opacity-30 transition-all"
            >
              Previous
            </button>
            <button
              disabled={page >= totalPages - 1}
              onClick={() => setPage(page + 1)}
              className="px-3 py-1.5 text-xs font-medium rounded-lg border border-slate-200 bg-white hover:bg-slate-50 disabled:opacity-30 transition-all"
            >
              Next
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
