"use client";

import { useEffect, useState } from "react";
import { Loader2, CheckCircle2, XCircle, Crosshair, FileText, X } from "lucide-react";

interface Comparison { keyword: string; brandPosition: number | null; competitorPosition: number | null; winner: string; gap: number | null }

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

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

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

  const wins = data?.filter((c) => c.winner === "brand").length ?? 0;
  const losses = data?.filter((c) => c.winner === "competitor").length ?? 0;

  return (
    <div className="bg-white rounded-xl border border-blue-200 overflow-hidden">
      <div className="px-5 py-3.5 border-b border-blue-100 bg-blue-50/40 flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Crosshair className="w-4 h-4 text-blue-600" />
          <h3 className="font-bold text-slate-800 text-sm">Ranking Comparison vs {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>

      {loading ? (
        <div className="px-5 py-12 text-center"><Loader2 className="w-6 h-6 text-blue-500 animate-spin mx-auto mb-2" /><p className="text-xs text-slate-500">Checking rankings — this may take 30 seconds...</p></div>
      ) : !data || data.length === 0 ? (
        <div className="px-5 py-8 text-center text-xs text-slate-400">No tracked keywords to compare. Add keywords in Rank Tracker first.</div>
      ) : (
        <>
          <div className="px-5 py-3 flex items-center gap-4 border-b border-slate-100 bg-slate-50/50">
            <span className="text-xs font-semibold text-green-600">You win: {wins}</span>
            <span className="text-xs font-semibold text-red-500">They win: {losses}</span>
            <span className="text-xs text-slate-400">({data.length} keywords compared)</span>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead><tr className="border-b border-slate-100 bg-slate-50/80 text-[10px] font-bold uppercase tracking-widest text-slate-400">
                <th className="px-4 py-2 text-left">Keyword</th>
                <th className="px-4 py-2 text-center">Your Pos</th>
                <th className="px-4 py-2 text-center">Their Pos</th>
                <th className="px-4 py-2 text-center">Winner</th>
                <th className="px-4 py-2 text-center">Gap</th>
              </tr></thead>
              <tbody>
                {data.map((c) => {
                  const youWin = c.winner === "brand";
                  return (
                    <tr key={c.keyword} className="border-b border-slate-50 hover:bg-slate-50">
                      <td className="px-4 py-2.5 font-medium text-slate-900">{c.keyword}</td>
                      <td className={`px-4 py-2.5 text-center font-bold tabular-nums ${youWin ? "text-green-600" : c.brandPosition != null ? "text-red-500" : "text-slate-400"}`}>{c.brandPosition ?? "—"}</td>
                      <td className={`px-4 py-2.5 text-center font-bold tabular-nums ${!youWin && c.competitorPosition != null ? "text-green-600" : "text-slate-600"}`}>{c.competitorPosition ?? "—"}</td>
                      <td className="px-4 py-2.5 text-center">{youWin ? <CheckCircle2 className="w-4 h-4 text-green-600 mx-auto" /> : c.winner === "competitor" ? <XCircle className="w-4 h-4 text-red-500 mx-auto" /> : <span className="text-slate-400">—</span>}</td>
                      <td className="px-4 py-2.5 text-center">
                        {c.gap != null ? <span className={`text-xs font-bold ${c.gap > 0 ? "text-green-600" : "text-red-500"}`}>{c.gap > 0 ? "+" : ""}{c.gap}</span> : "—"}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </>
      )}
    </div>
  );
}
