"use client";
import { useState, useMemo } from "react";
import { FileText, ArrowUp, ArrowDown, ArrowUpDown, ExternalLink } from "lucide-react";
import type { TableSpec } from "@/lib/services/analysis-schema";

type SortDir = "asc" | "desc";

function formatCell(value: string | number | undefined, format?: string): string {
  if (value === undefined || value === null) return "—";
  if (format === "number") return Number(value).toLocaleString();
  if (format === "percent") return `${value}%`;
  if (format === "currency") return `$${Number(value).toLocaleString()}`;
  return String(value);
}

function isUrl(value: unknown): value is string {
  if (typeof value !== "string") return false;
  return value.startsWith("http") || value.startsWith("/");
}

export function DataTableSection({ table }: { table: TableSpec }) {
  const [sortKey, setSortKey] = useState<string | null>(table.sortBy ?? null);
  const [sortDir, setSortDir] = useState<SortDir>(table.sortDir ?? "desc");

  const sortedRows = useMemo(() => {
    if (!sortKey) return table.rows;
    const sorted = [...table.rows].sort((a, b) => {
      const av = a[sortKey];
      const bv = b[sortKey];
      if (typeof av === "number" && typeof bv === "number") {
        return sortDir === "asc" ? av - bv : bv - av;
      }
      const as = String(av ?? "");
      const bs = String(bv ?? "");
      return sortDir === "asc" ? as.localeCompare(bs) : bs.localeCompare(as);
    });
    return sorted;
  }, [table.rows, sortKey, sortDir]);

  function toggleSort(key: string) {
    if (sortKey === key) {
      setSortDir(d => d === "asc" ? "desc" : "asc");
    } else {
      setSortKey(key);
      setSortDir("desc");
    }
  }

  return (
    <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
      <div className="px-4 py-3 border-b border-slate-100 flex items-center gap-2">
        <FileText className="w-3.5 h-3.5 text-brand-600" />
        <h3 className="text-sm font-bold text-slate-800">{table.title}</h3>
        <span className="ml-auto text-[10px] font-medium text-slate-400 bg-slate-50 px-2 py-0.5 rounded">
          {table.source}
        </span>
      </div>
      <div className="overflow-x-auto">
        <table className="w-full text-xs">
          <thead>
            <tr className="border-b border-slate-100 bg-slate-50">
              {table.columns.map(col => {
                const isSorted = sortKey === col.key;
                const alignCls = col.align === "right" ? "text-right" : col.align === "center" ? "text-center" : "text-left";
                return (
                  <th
                    key={col.key}
                    className={`px-3 py-2 font-bold text-[9px] text-slate-500 uppercase tracking-widest ${alignCls} cursor-pointer hover:bg-slate-100 transition-colors`}
                    onClick={() => toggleSort(col.key)}
                  >
                    <span className={`inline-flex items-center gap-1 ${col.align === "right" ? "flex-row-reverse" : ""}`}>
                      {col.label}
                      {isSorted ? (
                        sortDir === "asc" ? <ArrowUp className="w-2.5 h-2.5 text-brand-600" /> : <ArrowDown className="w-2.5 h-2.5 text-brand-600" />
                      ) : (
                        <ArrowUpDown className="w-2.5 h-2.5 text-slate-300" />
                      )}
                    </span>
                  </th>
                );
              })}
            </tr>
          </thead>
          <tbody>
            {sortedRows.map((row, i) => (
              <tr
                key={i}
                className={`border-b border-slate-50 hover:bg-brand-50/30 transition-colors ${i % 2 === 1 ? "bg-slate-50/40" : ""}`}
              >
                {table.columns.map(col => {
                  const value = row[col.key];
                  const alignCls = col.align === "right" ? "text-right" : col.align === "center" ? "text-center" : "text-left";
                  // URL rendering
                  if (isUrl(value)) {
                    const displayValue = String(value).length > 40 ? String(value).slice(0, 37) + "…" : String(value);
                    return (
                      <td key={col.key} className={`px-3 py-2 ${alignCls}`}>
                        <a
                          href={String(value).startsWith("http") ? String(value) : undefined}
                          target="_blank"
                          rel="noopener noreferrer"
                          title={String(value)}
                          className="inline-flex items-center gap-1 text-brand-600 hover:text-brand-700 hover:underline font-mono text-[11px]"
                        >
                          {displayValue}
                          {String(value).startsWith("http") && <ExternalLink className="w-2.5 h-2.5 shrink-0" />}
                        </a>
                      </td>
                    );
                  }
                  // Numeric/text cell
                  return (
                    <td key={col.key} className={`px-3 py-2 text-slate-700 ${alignCls} ${col.format === "number" || col.format === "currency" || col.format === "percent" ? "font-mono font-semibold tabular-nums" : ""}`}>
                      {formatCell(value, col.format)}
                    </td>
                  );
                })}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {sortedRows.length === 0 && (
        <div className="px-4 py-6 text-center text-[11px] text-slate-400">No data available</div>
      )}
    </div>
  );
}
