"use client";

import { useState, useEffect } from "react";
import { usePathname } from "next/navigation";
import Link from "next/link";
import { useBrand } from "@/context/brand-context";
import { Zap, TrendingUp, ArrowRight, X, Loader2, ShieldCheck } from "lucide-react";

/** Pages where the banner should NOT appear */
const EXCLUDED_PAGES = ["/settings", "/integrations", "/brands-hub", "/website-upload", "/onboarding", "/ai-strategist"];

// ─── Component ───────────────────────────────────────────────────────────────

export function NextBestAction() {
  const pathname = usePathname();
  const { brand, getSourceStatus } = useBrand();
  const [dismissed, setDismissed] = useState(false);
  const [state, setState] = useState<"loading" | "none" | "running" | "completed">("loading");
  const [action, setAction] = useState<{ title: string; description: string; errorCount: number; warningCount: number; crawlHealth: number } | null>(null);

  useEffect(() => {
    if (EXCLUDED_PAGES.some(p => pathname.startsWith(p))) return;

    // Check source registry — only show NBA for completed, real crawl
    const auditSource = getSourceStatus("technical_audit");
    if (!auditSource || auditSource.status !== "connected") {
      // Allow "running" through to show the running state below
      if (auditSource?.status !== "running") {
        setState("none");
        return;
      }
    }

    fetch(`/api/technical-audit?brandId=${brand.id}`)
      .then(res => res.ok ? res.json() : null)
      .then(data => {
        if (!data) { setState("none"); return; }
        if (data.running) { setState("running"); return; }
        if (!data.audit) { setState("none"); return; }

        const a = data.audit;
        const totalIssues = (a.errorCount ?? 0) + (a.warningCount ?? 0);
        if (totalIssues === 0) { setState("none"); return; }
        if ((a.pagesScanned ?? 0) === 0) { setState("none"); return; }

        setAction({
          title: `Fix ${a.errorCount} error${a.errorCount !== 1 ? "s" : ""} and ${a.warningCount} warning${a.warningCount !== 1 ? "s" : ""} found on ${brand.domain}`,
          description: `Your latest audit scanned ${a.pagesScanned} page${a.pagesScanned !== 1 ? "s" : ""} and scored ${a.crawlHealth}/100 with ${totalIssues} open issues.`,
          errorCount: a.errorCount,
          warningCount: a.warningCount,
          crawlHealth: a.crawlHealth,
        });
        setState("completed");
      })
      .catch(() => setState("none"));
  }, [brand.id, brand.domain, pathname, getSourceStatus]);

  if (dismissed) return null;
  if (EXCLUDED_PAGES.some(p => pathname.startsWith(p))) return null;
  if (state === "loading" || state === "none") return null;

  // Running state
  if (state === "running") {
    return (
      <div className="mx-6 mt-4 mb-0 rounded-xl border border-slate-200 bg-slate-50 overflow-hidden">
        <div className="px-5 py-3 flex items-center gap-3">
          <Loader2 className="w-4 h-4 text-slate-400 animate-spin shrink-0" />
          <p className="text-xs text-slate-500">Technical Audit is running — recommendations will appear when complete.</p>
          <span className="flex-1" />
          <button onClick={() => setDismissed(true)} className="text-slate-400 hover:text-slate-600 transition-colors shrink-0" title="Dismiss">
            <X className="w-4 h-4" />
          </button>
        </div>
      </div>
    );
  }

  // Completed with real evidence
  if (!action) return null;
  const onAuditPage = pathname.startsWith("/technical-audit");

  return (
    <div className="mx-6 mt-4 mb-0 rounded-xl border border-amber-200 bg-amber-50 overflow-hidden">
      <div className="px-5 py-3.5 flex items-start gap-3">
        <div className="w-8 h-8 rounded-lg bg-white border border-amber-200 flex items-center justify-center shrink-0 mt-0.5">
          <Zap className="w-4 h-4 text-amber-600" />
        </div>

        <div className="flex-1 min-w-0">
          <p className="text-xs font-bold uppercase tracking-widest text-slate-400 mb-1">Next Best Action</p>
          <p className="text-sm font-bold text-slate-900">{action.title}</p>
          <p className="text-xs text-slate-600 leading-relaxed mt-0.5">{action.description}</p>

          <div className="flex flex-wrap items-center gap-2 mt-2.5">
            <span className="inline-flex items-center gap-1 text-[10px] font-semibold text-red-700 bg-white border border-red-200 rounded-full px-2 py-0.5">
              {action.errorCount} error{action.errorCount !== 1 ? "s" : ""}
            </span>
            <span className="inline-flex items-center gap-1 text-[10px] font-semibold text-amber-700 bg-white border border-amber-200 rounded-full px-2 py-0.5">
              {action.warningCount} warning{action.warningCount !== 1 ? "s" : ""}
            </span>
            <span className="inline-flex items-center gap-1 text-[10px] font-semibold text-slate-600 bg-white border border-slate-200 rounded-full px-2 py-0.5">
              <ShieldCheck className="w-3 h-3" />
              Health: {action.crawlHealth}/100
            </span>

            <span className="flex-1" />

            {!onAuditPage && (
              <Link
                href="/technical-audit"
                className="inline-flex items-center gap-1.5 px-3.5 py-1.5 rounded-lg text-xs font-semibold text-white bg-slate-900 hover:bg-slate-800 transition-colors"
              >
                View Audit
                <ArrowRight className="w-3 h-3" />
              </Link>
            )}
          </div>
        </div>

        <button onClick={() => setDismissed(true)} className="text-slate-400 hover:text-slate-600 transition-colors shrink-0 mt-0.5" title="Dismiss">
          <X className="w-4 h-4" />
        </button>
      </div>
    </div>
  );
}
