"use client";

import { useState, useCallback } from "react";
import { Search, Loader2, Sparkles, ChevronDown, ChevronUp, ExternalLink, CheckCircle2, Info } from "lucide-react";

interface GapOpp { domain: string; reason: string; difficulty: string; outreach: string; competitorBacklinks?: string[] }

interface AcquisitionStep {
  title: string;
  action: string;
  effort: string;
  linkType: string;
  dofollow: boolean;
}

interface Strategy {
  steps: AcquisitionStep[];
  difficultyExplanation: string;
  estimatedImpact: string;
  loading: boolean;
  error?: string;
}

interface Props { brandId: string }

const DIFF_COLORS: Record<string, string> = {
  easy: "bg-green-50 text-green-700 border-green-200",
  medium: "bg-amber-50 text-amber-700 border-amber-200",
  hard: "bg-red-50 text-red-700 border-red-200",
};

export default function GapAnalysis({ brandId }: Props) {
  const [competitor, setCompetitor] = useState("");
  const [loading, setLoading] = useState(false);
  const [gaps, setGaps] = useState<GapOpp[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [expanded, setExpanded] = useState<string | null>(null);
  const [strategies, setStrategies] = useState<Record<string, Strategy>>({});
  const [filter, setFilter] = useState<"all" | "easy" | "hard">("all");

  async function analyze() {
    if (!competitor.trim() || loading) return;
    setLoading(true); setError(null); setGaps(null); setStrategies({});
    try {
      const res = await fetch("/api/backlinks/gap-analysis", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ brandId, competitorDomain: competitor.trim() }),
      });
      if (res.ok) { const d = await res.json(); setGaps(d.gaps || []); }
      else { const d = await res.json().catch(() => ({})); setError(d.error || "Analysis failed"); }
    } catch { setError("Network error"); }
    setLoading(false);
  }

  const loadStrategy = useCallback(async (gap: GapOpp) => {
    if (strategies[gap.domain]?.steps?.length) return;
    setStrategies((prev) => ({
      ...prev,
      [gap.domain]: { steps: [], difficultyExplanation: "", estimatedImpact: "", loading: true },
    }));
    try {
      const res = await fetch("/api/backlinks/acquisition-strategy", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          brandId, domain: gap.domain, difficulty: gap.difficulty,
          competitorBacklinks: gap.competitorBacklinks ?? [],
        }),
      });
      if (!res.ok) {
        setStrategies((prev) => ({ ...prev, [gap.domain]: { steps: [], difficultyExplanation: "", estimatedImpact: "", loading: false, error: `HTTP ${res.status}` } }));
        return;
      }
      const data = await res.json() as Strategy;
      setStrategies((prev) => ({ ...prev, [gap.domain]: { ...data, loading: false } }));
    } catch (err) {
      setStrategies((prev) => ({ ...prev, [gap.domain]: { steps: [], difficultyExplanation: "", estimatedImpact: "", loading: false, error: err instanceof Error ? err.message : "Network error" } }));
    }
  }, [brandId, strategies]);

  function toggle(domain: string, gap: GapOpp) {
    setExpanded((cur) => {
      const next = cur === domain ? null : domain;
      if (next === domain) loadStrategy(gap);
      return next;
    });
  }

  const filtered = gaps?.filter((g) => {
    if (filter === "all") return true;
    if (filter === "easy") return g.difficulty === "easy";
    if (filter === "hard") return g.difficulty === "hard";
    return true;
  }) ?? [];

  return (
    <div className="bg-gradient-to-br from-violet-50 via-white to-blue-50 rounded-xl border border-violet-200 p-6">
      <div className="mb-4">
        <h3 className="text-base font-bold text-slate-900 flex items-center gap-2">
          <Sparkles className="w-4 h-4 text-violet-600" />
          Backlink Gap Analysis
        </h3>
        <p className="text-xs text-slate-600 mt-1 max-w-2xl">
          Compare your backlink profile against a competitor to find link-building opportunities. Click any opportunity for an AI-generated acquisition strategy.
        </p>
      </div>
      <div className="flex items-center gap-2 mb-4">
        <input
          value={competitor}
          onChange={(e) => setCompetitor(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && analyze()}
          placeholder="Competitor domain (e.g. competitor.com)"
          className="flex-1 px-4 py-2.5 text-sm border border-slate-200 bg-white rounded-lg focus:outline-none focus:ring-2 focus:ring-violet-500/40 focus:border-violet-400"
        />
        <button
          onClick={analyze}
          disabled={loading || !competitor.trim()}
          className="flex items-center gap-1.5 px-5 py-2.5 bg-violet-600 text-white text-sm font-semibold rounded-lg hover:bg-violet-700 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Search className="w-4 h-4" />} Find Gaps
        </button>
      </div>

      {gaps && gaps.length > 0 && (
        <div className="flex items-center gap-1.5 mb-3">
          {[
            { key: "all", label: `All (${gaps.length})` },
            { key: "easy", label: `Easy Wins (${gaps.filter((g) => g.difficulty === "easy").length})` },
            { key: "hard", label: `Hard (${gaps.filter((g) => g.difficulty === "hard").length})` },
          ].map((f) => (
            <button
              key={f.key}
              onClick={() => setFilter(f.key as typeof filter)}
              className={`text-[10px] font-semibold px-2.5 py-1 rounded-lg ${filter === f.key ? "bg-violet-600 text-white" : "bg-white border border-slate-200 text-slate-600 hover:bg-slate-50"}`}
            >
              {f.label}
            </button>
          ))}
        </div>
      )}

      {error && <p className="text-xs text-red-600 mb-2">{error}</p>}
      {gaps && gaps.length === 0 && <p className="text-xs text-slate-500">No gap opportunities found for this competitor.</p>}

      {filtered.length > 0 && (
        <div className="space-y-2">
          {filtered.map((g) => {
            const isOpen = expanded === g.domain;
            const strategy = strategies[g.domain];
            return (
              <div key={g.domain} className="bg-white rounded-lg border border-slate-200 overflow-hidden">
                <button
                  onClick={() => toggle(g.domain, g)}
                  className="w-full flex items-start gap-3 p-3 text-left hover:bg-slate-50"
                >
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-0.5">
                      <span className="text-xs font-bold text-slate-800">{g.domain}</span>
                      <span className={`text-[9px] font-bold px-1.5 py-0.5 rounded capitalize border ${DIFF_COLORS[g.difficulty] || DIFF_COLORS.medium}`}>{g.difficulty}</span>
                    </div>
                    <p className="text-[11px] text-slate-500">{g.reason}</p>
                  </div>
                  {isOpen ? <ChevronUp className="w-4 h-4 text-slate-400 shrink-0" /> : <ChevronDown className="w-4 h-4 text-slate-400 shrink-0" />}
                </button>

                {isOpen && (
                  <div className="border-t border-slate-100 bg-slate-50/50 px-3 py-3 space-y-3">
                    {strategy?.loading && (
                      <div className="space-y-2">
                        <p className="text-[10px] text-slate-500 italic flex items-center gap-1.5">
                          <Loader2 className="w-3 h-3 animate-spin" /> Generating acquisition strategy…
                        </p>
                        {[0, 1, 2].map((i) => (
                          <div key={i} className="bg-white rounded border border-slate-200 p-2 animate-pulse">
                            <div className="h-3 w-1/3 bg-slate-200 rounded mb-2" />
                            <div className="h-2.5 w-full bg-slate-100 rounded" />
                          </div>
                        ))}
                      </div>
                    )}

                    {strategy?.error && (
                      <p className="text-xs text-amber-700 bg-amber-50 border border-amber-200 rounded p-2">
                        Couldn&apos;t generate strategy: {strategy.error}. Original suggestion: {g.outreach}
                      </p>
                    )}

                    {strategy && !strategy.loading && !strategy.error && (
                      <>
                        {/* Difficulty explanation */}
                        {strategy.difficultyExplanation && (
                          <div className="bg-white rounded border border-slate-200 p-2 flex items-start gap-2">
                            <Info className="w-3.5 h-3.5 text-slate-400 shrink-0 mt-0.5" />
                            <p className="text-[11px] text-slate-700">{strategy.difficultyExplanation}</p>
                          </div>
                        )}

                        {/* AI Acquisition Strategy steps */}
                        <div>
                          <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1.5 flex items-center gap-1">
                            <Sparkles className="w-3 h-3 text-amber-500" /> AI Acquisition Strategy
                          </p>
                          <ol className="space-y-2">
                            {strategy.steps.map((step, idx) => (
                              <li key={idx} className="bg-white rounded border border-slate-200 p-2.5">
                                <div className="flex items-start gap-2">
                                  <span className="text-[10px] font-bold text-violet-600 bg-violet-50 border border-violet-200 rounded-full w-5 h-5 flex items-center justify-center shrink-0 mt-0.5">{idx + 1}</span>
                                  <div className="flex-1 min-w-0">
                                    <p className="text-xs font-bold text-slate-800">{step.title}</p>
                                    <p className="text-[11px] text-slate-600 mt-0.5 leading-relaxed">{step.action}</p>
                                    <div className="flex items-center gap-1.5 mt-1.5 flex-wrap">
                                      <span className="text-[9px] font-semibold text-slate-500 bg-slate-100 px-1.5 py-0.5 rounded">{step.effort}</span>
                                      <span className="text-[9px] font-semibold text-blue-700 bg-blue-50 border border-blue-200 px-1.5 py-0.5 rounded capitalize">{step.linkType.replace(/_/g, " ")}</span>
                                      <span className={`text-[9px] font-semibold px-1.5 py-0.5 rounded ${step.dofollow ? "bg-emerald-50 text-emerald-700 border border-emerald-200" : "bg-slate-50 text-slate-500 border border-slate-200"}`}>
                                        {step.dofollow ? "dofollow" : "nofollow"}
                                      </span>
                                    </div>
                                  </div>
                                </div>
                              </li>
                            ))}
                          </ol>
                        </div>

                        {/* Estimated impact */}
                        {strategy.estimatedImpact && (
                          <div className="bg-emerald-50 border border-emerald-200 rounded p-2">
                            <p className="text-[10px] font-bold uppercase tracking-widest text-emerald-700 mb-0.5">Estimated impact</p>
                            <p className="text-[11px] text-emerald-900">{strategy.estimatedImpact}</p>
                          </div>
                        )}

                        {/* Action buttons */}
                        <div className="flex items-center gap-2">
                          <a
                            href={`https://${g.domain}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="inline-flex items-center gap-1 text-[10px] font-semibold text-violet-700 bg-white border border-violet-200 rounded-lg px-2.5 py-1 hover:bg-violet-50"
                          >
                            <ExternalLink className="w-3 h-3" /> Open {g.domain}
                          </a>
                          <button className="inline-flex items-center gap-1 text-[10px] font-semibold text-slate-600 bg-white border border-slate-200 rounded-lg px-2.5 py-1 hover:bg-slate-50">
                            <CheckCircle2 className="w-3 h-3" /> Track Progress
                          </button>
                        </div>
                      </>
                    )}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
