"use client";

import { useRouter } from "next/navigation";
import { FileText, Loader2 } from "lucide-react";
import { useState } from "react";

interface PlanItem { title: string; targetKeyword: string; relatedKeywords: string[]; intent: string; format: string; priority: string }

const PRIO_CLS: Record<string, string> = { 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 FORMAT_CLS: Record<string, string> = { blog: "bg-violet-50 text-violet-700", "landing page": "bg-green-50 text-green-700", landing: "bg-green-50 text-green-700", "service page": "bg-blue-50 text-blue-700", service: "bg-blue-50 text-blue-700" };

interface Props { items: PlanItem[]; brandId: string }

export default function ContentPlan({ items, brandId }: Props) {
  const router = useRouter();
  const [creating, setCreating] = useState<string | null>(null);

  async function createBrief(item: PlanItem) {
    setCreating(item.targetKeyword);
    try {
      const res = await fetch("/api/keyword-research/send-to-brief", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ brandId, keyword: item.targetKeyword, relatedKeywords: item.relatedKeywords, type: "seo" }),
      });
      if (res.ok) { const data = await res.json(); router.push(`/content-brief?briefId=${data.briefId}`); }
    } catch { /* swallow */ }
    setCreating(null);
  }

  if (items.length === 0) return null;

  return (
    <div className="bg-white rounded-xl border border-violet-200 overflow-hidden">
      <div className="px-5 py-3.5 border-b border-violet-100 bg-violet-50/40 flex items-center gap-2">
        <FileText className="w-4 h-4 text-violet-600" />
        <h3 className="font-bold text-slate-800 text-sm">AI Content Plan</h3>
        <span className="ml-auto text-[10px] text-slate-400">{items.length} pieces recommended</span>
      </div>
      <div className="divide-y divide-slate-100">
        {items.map((item, i) => {
          const pCls = PRIO_CLS[item.priority] || PRIO_CLS.P3;
          const fCls = FORMAT_CLS[item.format.toLowerCase()] || "bg-slate-50 text-slate-600";
          return (
            <div key={i} className="px-5 py-3 flex items-center gap-3 hover:bg-slate-50">
              <span className={`text-[9px] font-bold uppercase tracking-wider rounded-full px-2 py-0.5 border shrink-0 ${pCls}`}>{item.priority}</span>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-semibold text-slate-900 truncate">{item.title}</p>
                <p className="text-xs text-slate-500 truncate">Target: {item.targetKeyword} · {item.relatedKeywords.length} related</p>
              </div>
              <span className={`text-[9px] font-bold rounded-full px-2 py-0.5 shrink-0 ${fCls}`}>{item.format}</span>
              <button onClick={() => createBrief(item)} disabled={creating === item.targetKeyword} className="flex items-center gap-1 px-2.5 py-1.5 rounded-lg border border-slate-200 text-[11px] font-semibold text-brand-700 hover:bg-brand-50 shrink-0 disabled:opacity-50">
                {creating === item.targetKeyword ? <Loader2 className="w-3 h-3 animate-spin" /> : <FileText className="w-3 h-3" />}
                Create Brief
              </button>
            </div>
          );
        })}
      </div>
    </div>
  );
}
