"use client";

import { useEffect, useState } from "react";
import { Loader2, AlertTriangle, TrendingUp, Target, Sparkles, X } from "lucide-react";

interface Analysis {
  summary: string;
  threats: Array<{ title: string; description: string; severity: string }>;
  opportunities: Array<{ title: string; description: string; impact: string }>;
  contentGaps: Array<{ topic: string; competitorUrl?: string; suggestedAction: string }>;
  rankingBattles: Array<{ keyword: string; brandPos: number | null; compPos: number | null; recommendation: string }>;
  strategicRecommendation: string;
}

const SEV_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-slate-50 text-slate-600 border-slate-200" };

interface Props { competitorId: string; competitorDomain: string; onClose: () => void }

export default function AiAnalysisPanel({ competitorId, competitorDomain, onClose }: Props) {
  const [data, setData] = useState<Analysis | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(`/api/competitors/${competitorId}/analyze`, { method: "POST" })
      .then((r) => r.ok ? r.json() : null)
      .then((d) => setData(d?.analysis ?? null))
      .finally(() => setLoading(false));
  }, [competitorId]);

  if (loading) return (
    <div className="bg-white rounded-xl border border-violet-200 px-5 py-12 text-center">
      <Loader2 className="w-6 h-6 text-violet-500 animate-spin mx-auto mb-2" />
      <p className="text-xs text-slate-500">AI is analyzing {competitorDomain}...</p>
    </div>
  );
  if (!data) return null;

  return (
    <div className="bg-white rounded-xl border border-violet-200 overflow-hidden space-y-0">
      <div className="px-5 py-3.5 border-b border-violet-100 bg-violet-50/40 flex items-center justify-between">
        <div className="flex items-center gap-2"><Sparkles className="w-4 h-4 text-violet-600" /><h3 className="font-bold text-slate-800 text-sm">AI Analysis: {competitorDomain}</h3></div>
        <button onClick={onClose} className="p-1 rounded-md hover:bg-white text-slate-400"><X className="w-4 h-4" /></button>
      </div>

      {/* Summary */}
      <div className="px-5 py-4 border-b border-slate-100"><p className="text-sm text-slate-700 leading-relaxed">{data.summary}</p></div>

      {/* Strategic recommendation */}
      {data.strategicRecommendation && (
        <div className="px-5 py-4 border-b border-slate-100 bg-brand-50/30">
          <p className="text-[10px] font-bold uppercase tracking-widest text-brand-600 mb-1">Key Recommendation</p>
          <p className="text-sm text-slate-800 font-medium">{data.strategicRecommendation}</p>
        </div>
      )}

      {/* Threats */}
      {data.threats.length > 0 && (
        <div className="px-5 py-4 border-b border-slate-100">
          <div className="flex items-center gap-1.5 mb-3"><AlertTriangle className="w-3.5 h-3.5 text-red-500" /><span className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Threats</span></div>
          <div className="space-y-2">{data.threats.map((t, i) => (
            <div key={i} className="flex items-start gap-2">
              <span className={`text-[9px] font-bold uppercase tracking-wider rounded-full px-2 py-0.5 border shrink-0 mt-0.5 ${SEV_CLS[t.severity] || SEV_CLS.medium}`}>{t.severity}</span>
              <div><p className="text-xs font-semibold text-slate-900">{t.title}</p><p className="text-[11px] text-slate-600">{t.description}</p></div>
            </div>
          ))}</div>
        </div>
      )}

      {/* Opportunities */}
      {data.opportunities.length > 0 && (
        <div className="px-5 py-4 border-b border-slate-100">
          <div className="flex items-center gap-1.5 mb-3"><TrendingUp className="w-3.5 h-3.5 text-green-600" /><span className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Opportunities</span></div>
          <div className="space-y-2">{data.opportunities.map((o, i) => (
            <div key={i} className="flex items-start gap-2">
              <span className={`text-[9px] font-bold uppercase tracking-wider rounded-full px-2 py-0.5 border shrink-0 mt-0.5 ${o.impact === "high" ? "bg-green-50 text-green-700 border-green-200" : "bg-blue-50 text-blue-700 border-blue-200"}`}>{o.impact}</span>
              <div><p className="text-xs font-semibold text-slate-900">{o.title}</p><p className="text-[11px] text-slate-600">{o.description}</p></div>
            </div>
          ))}</div>
        </div>
      )}

      {/* Content gaps */}
      {data.contentGaps.length > 0 && (
        <div className="px-5 py-4 border-b border-slate-100">
          <div className="flex items-center gap-1.5 mb-3"><Target className="w-3.5 h-3.5 text-blue-600" /><span className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Content Gaps</span></div>
          <div className="space-y-2">{data.contentGaps.map((g, i) => (
            <div key={i} className="bg-slate-50 rounded-lg px-3 py-2">
              <p className="text-xs font-semibold text-slate-900">{g.topic}</p>
              <p className="text-[11px] text-slate-600">{g.suggestedAction}</p>
            </div>
          ))}</div>
        </div>
      )}

      {/* Ranking battles */}
      {data.rankingBattles.length > 0 && (
        <div className="px-5 py-4">
          <div className="flex items-center gap-1.5 mb-3"><Sparkles className="w-3.5 h-3.5 text-violet-600" /><span className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Ranking Battles</span></div>
          <div className="space-y-2">{data.rankingBattles.map((b, i) => (
            <div key={i} className="flex items-center gap-3 text-xs">
              <span className="font-medium text-slate-800 flex-1">{b.keyword}</span>
              <span className="text-slate-500">You: {b.brandPos ?? "—"}</span>
              <span className="text-slate-500">Them: {b.compPos ?? "—"}</span>
              <span className="text-[11px] text-brand-700 max-w-[200px] truncate">{b.recommendation}</span>
            </div>
          ))}</div>
        </div>
      )}
    </div>
  );
}
