"use client";

import { useState } from "react";
import { ChevronDown, Plus } from "lucide-react";

interface Keyword { keyword: string; searchVolume?: number | null; difficulty?: number | null; cpc?: number | null; intent?: string | null }
interface Cluster { name: string; keywords: string[]; contentStrategy: string; priority: string; estimatedTrafficPotential: string }

const PRIORITY_CLS: Record<string, string> = { high: "bg-red-50 text-red-700 border-red-200", medium: "bg-amber-50 text-amber-700 border-amber-200", low: "bg-blue-50 text-blue-700 border-blue-200", P1: "bg-red-50 text-red-700 border-red-200", P2: "bg-amber-50 text-amber-700 border-amber-200", P3: "bg-blue-50 text-blue-700 border-blue-200" };
const INTENT_CLS: Record<string, string> = { informational: "bg-blue-50 text-blue-700", transactional: "bg-green-50 text-green-700", commercial: "bg-violet-50 text-violet-700", navigational: "bg-slate-100 text-slate-600" };

function diffColor(d: number | null | undefined): string {
  if (d == null) return "bg-slate-200";
  if (d <= 30) return "bg-green-500";
  if (d <= 60) return "bg-amber-400";
  return "bg-red-500";
}

interface Props {
  cluster: Cluster;
  allKeywords: Keyword[];
  selected: Set<string>;
  onToggle: (kw: string) => void;
}

export default function TopicClusterCard({ cluster, allKeywords, selected, onToggle }: Props) {
  const [open, setOpen] = useState(false);
  const kwMap = new Map(allKeywords.map((k) => [k.keyword.toLowerCase(), k]));
  const clusterKws = cluster.keywords.map((kw) => kwMap.get(kw.toLowerCase()) || { keyword: kw }).slice(0, 20);
  const pCls = PRIORITY_CLS[cluster.priority] || PRIORITY_CLS.medium;

  return (
    <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
      <button onClick={() => setOpen(!open)} className="w-full flex items-center gap-3 px-5 py-4 text-left hover:bg-slate-50">
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 mb-1">
            <h3 className="text-sm font-bold text-slate-900">{cluster.name}</h3>
            <span className={`text-[9px] font-bold uppercase tracking-wider rounded-full px-2 py-0.5 border ${pCls}`}>{cluster.priority}</span>
          </div>
          <p className="text-xs text-slate-500">{cluster.keywords.length} keywords · {cluster.estimatedTrafficPotential}</p>
        </div>
        <p className="text-xs text-slate-500 max-w-[200px] truncate hidden sm:block">{cluster.contentStrategy}</p>
        <ChevronDown className={`w-4 h-4 text-slate-400 transition-transform shrink-0 ${open ? "rotate-180" : ""}`} />
      </button>
      {open && (
        <div className="border-t border-slate-100">
          <div className="px-5 py-3 bg-brand-50/30 border-b border-slate-100">
            <p className="text-xs text-slate-700 leading-relaxed"><span className="font-semibold text-slate-900">Content strategy:</span> {cluster.contentStrategy}</p>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead><tr className="text-[10px] font-bold uppercase tracking-widest text-slate-400 border-b border-slate-100">
                <th className="w-8 px-3 py-2" /><th className="px-3 py-2 text-left">Keyword</th><th className="px-3 py-2 text-right">Volume</th><th className="px-3 py-2 w-24">Difficulty</th><th className="px-3 py-2 text-right">CPC</th><th className="px-3 py-2">Intent</th>
              </tr></thead>
              <tbody>
                {clusterKws.map((k) => (
                  <tr key={k.keyword} className="border-b border-slate-50 hover:bg-slate-50">
                    <td className="px-3 py-2"><input type="checkbox" checked={selected.has(k.keyword)} onChange={() => onToggle(k.keyword)} className="rounded" /></td>
                    <td className="px-3 py-2 font-medium text-slate-800">{k.keyword}</td>
                    <td className="px-3 py-2 text-right text-xs text-slate-600 tabular-nums">{k.searchVolume?.toLocaleString() ?? "—"}</td>
                    <td className="px-3 py-2">
                      <div className="flex items-center gap-2">
                        <div className="flex-1 h-1.5 rounded-full bg-slate-100 overflow-hidden"><div className={`h-full rounded-full ${diffColor(k.difficulty)}`} style={{ width: `${k.difficulty ?? 0}%` }} /></div>
                        <span className="text-[10px] text-slate-500 w-5 text-right tabular-nums">{k.difficulty ?? "—"}</span>
                      </div>
                    </td>
                    <td className="px-3 py-2 text-right text-xs text-slate-500 tabular-nums">{k.cpc != null ? `$${k.cpc.toFixed(2)}` : "—"}</td>
                    <td className="px-3 py-2">{k.intent && <span className={`text-[9px] font-bold rounded-full px-2 py-0.5 ${INTENT_CLS[k.intent] || INTENT_CLS.informational}`}>{k.intent}</span>}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}
