"use client";

/**
 * Reusable keyword data table with checkboxes, sorting, and compact
 * styling. Used by Quick Wins, Gap Analysis, Questions, and Avoid panels.
 */

import { useState } from "react";
import Link from "next/link";
import { ArrowUpDown, Check, Plus } from "lucide-react";
import { AiBadgesForItem, type AiIndicatorData } from "@/components/ai-badge";
import { IntentBadge, type IntentType } from "@/components/intent-badge";

export interface KwRow {
  keyword: string;
  volume?: number | null;
  difficulty?: number | null;
  position?: number | null;
  action?: string;
  reason?: string;
  contentType?: string;
  intent?: IntentType | string | null;
}

type SortKey = "keyword" | "volume" | "difficulty" | "position";

interface Props {
  rows: KwRow[];
  columns: Array<{ key: SortKey | "action" | "reason" | "contentType" | "track"; label: string }>;
  selected: Set<string>;
  onToggle: (kw: string) => void;
  accent?: string;
  trackedKeywords?: Set<string>;
  onTrack?: (keyword: string) => void | Promise<void>;
  aiData?: Record<string, AiIndicatorData>;
}

const DIFF_COLOR = (d: number | null | undefined) => d == null ? "bg-slate-200" : d <= 30 ? "bg-green-500" : d <= 60 ? "bg-amber-400" : "bg-red-500";

export default function KeywordTable({ rows, columns, selected, onToggle, accent = "border-slate-200", trackedKeywords, onTrack, aiData }: Props) {
  const [sortKey, setSortKey] = useState<SortKey>("volume");
  const [sortDir, setSortDir] = useState<"asc" | "desc">("desc");

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

  const sorted = [...rows].sort((a, b) => {
    const av = a[sortKey] ?? (sortDir === "asc" ? 999999 : -1);
    const bv = b[sortKey] ?? (sortDir === "asc" ? 999999 : -1);
    if (typeof av === "string" && typeof bv === "string") return sortDir === "asc" ? av.localeCompare(bv) : bv.localeCompare(av);
    return sortDir === "asc" ? Number(av) - Number(bv) : Number(bv) - Number(av);
  });

  const th = "px-3 py-2 text-[10px] font-bold uppercase tracking-widest text-slate-400";

  return (
    <div className={`bg-white rounded-xl border ${accent} overflow-hidden`}>
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead><tr className="border-b border-slate-100 bg-slate-50/80">
            <th className="w-8 px-3 py-2" />
            {columns.map((col) => {
              const sortable = ["keyword", "volume", "difficulty", "position"].includes(col.key);
              const leftAlign = col.key === "keyword" || col.key === "action" || col.key === "reason" || col.key === "contentType";
              const centerAlign = col.key === "track";
              return (
                <th key={col.key} className={`${th} ${leftAlign ? "text-left" : centerAlign ? "text-center" : "text-right"} ${sortable ? "cursor-pointer hover:text-slate-700" : ""}`} onClick={sortable ? () => toggleSort(col.key as SortKey) : undefined}>
                  <span className="inline-flex items-center gap-1">{col.label}{sortable && sortKey === col.key && <ArrowUpDown className="w-2.5 h-2.5" />}</span>
                </th>
              );
            })}
            {aiData && <th className={`${th} text-center`}>AI</th>}
          </tr></thead>
          <tbody>
            {sorted.map((row) => (
              <tr key={row.keyword} className="border-b border-slate-50 hover:bg-slate-50">
                <td className="px-3 py-2"><input type="checkbox" checked={selected.has(row.keyword)} onChange={() => onToggle(row.keyword)} className="rounded" /></td>
                {columns.map((col) => {
                  if (col.key === "keyword") return <td key={col.key} className="px-3 py-2 font-medium text-slate-800">{row.keyword}</td>;
                  if (col.key === "volume") return <td key={col.key} className="px-3 py-2 text-right text-xs tabular-nums text-slate-600">{row.volume?.toLocaleString() ?? "—"}</td>;
                  if (col.key === "difficulty") return (
                    <td key={col.key} className="px-3 py-2">
                      <div className="flex items-center gap-1.5 justify-end">
                        <div className="w-12 h-1.5 rounded-full bg-slate-100 overflow-hidden"><div className={`h-full rounded-full ${DIFF_COLOR(row.difficulty)}`} style={{ width: `${row.difficulty ?? 0}%` }} /></div>
                        <span className="text-[10px] text-slate-500 w-5 text-right tabular-nums">{row.difficulty ?? "—"}</span>
                      </div>
                    </td>
                  );
                  if (col.key === "position") return <td key={col.key} className="px-3 py-2 text-right text-xs tabular-nums text-slate-600">{row.position ?? "—"}</td>;
                  if (col.key === "track") {
                    const isTracked = trackedKeywords?.has(row.keyword.toLowerCase()) ?? false;
                    return (
                      <td key={col.key} className="px-3 py-2 text-center">
                        {isTracked ? (
                          <Link
                            href="/rank-tracker"
                            title="Already in Rank Tracker — click to view"
                            className="inline-flex items-center gap-1 text-[10px] font-bold uppercase tracking-wider bg-green-50 text-green-700 border border-green-200 rounded-full px-2 py-0.5 hover:bg-green-100 transition-colors"
                          >
                            <Check className="w-2.5 h-2.5" /> Tracking
                          </Link>
                        ) : (
                          <button
                            onClick={() => onTrack?.(row.keyword)}
                            disabled={!onTrack}
                            className="inline-flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wider bg-white text-brand-600 border border-brand-200 rounded-full px-2 py-0.5 hover:bg-brand-50 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
                          >
                            <Plus className="w-2.5 h-2.5" /> Track
                          </button>
                        )}
                      </td>
                    );
                  }
                  const text = row[col.key as keyof KwRow] as string | undefined;
                  return <td key={col.key} className="px-3 py-2 text-xs text-slate-600">{text || "—"}</td>;
                })}
                {row.intent && row.intent !== "unknown" && (
                  <td className="px-3 py-2 text-center">
                    <IntentBadge intent={row.intent as IntentType} />
                  </td>
                )}
                {aiData && (
                  <td className="px-3 py-2 text-center">
                    <AiBadgesForItem data={aiData[row.keyword] ?? null} />
                  </td>
                )}
              </tr>
            ))}
            {sorted.length === 0 && <tr><td colSpan={columns.length + 1} className="py-8 text-center text-xs text-slate-400">No keywords in this category.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  );
}
