"use client";

/**
 * Backlinks Monitoring — Full dashboard for backlink tracking,
 * quality analysis, toxic detection, gap analysis, and trends.
 */

import { useState, useEffect, useCallback } from "react";
import { useBrand } from "@/context/brand-context";
import { useBackgroundTasks } from "@/lib/stores/task-store";
import { Link2, Loader2, RefreshCw, Globe } from "lucide-react";

import OverviewCards from "@/components/backlinks/overview-cards";
import QualityChart from "@/components/backlinks/quality-chart";
import BacklinkTable from "@/components/backlinks/backlink-table";
import ToxicPanel from "@/components/backlinks/toxic-panel";
import GapAnalysis from "@/components/backlinks/gap-analysis";
import TrendChart from "@/components/backlinks/trend-chart";
import FeatureGate from "@/components/plan/feature-gate";

interface Summary {
  total: number; totalDomains: number; newThisMonth: number;
  lostThisMonth: number; avgDomainAuthority: number; toxicCount: number;
  qualityDistribution: Record<string, number>;
  health?: {
    healthy: number;
    lowRisk: number;
    moderate: number;
    highRisk: number;
    toxic: number;
  };
}

interface Backlink {
  id: string; sourceDomain: string; sourceUrl: string; targetUrl: string;
  anchorText: string | null; linkType: string | null; domainAuthority: number | null;
  relevanceScore: number | null; toxicityScore: number | null; qualityTier: string | null;
  toxicityReasons?: string[]; status: string; firstSeenAt: string;
}

interface TopPage { targetUrl: string; backlinkCount: number; domainCount: number; avgAuthority: number }

// Backlinks is a Professional+ feature. FeatureGate wrapper catches
// direct navigations that bypass the sidebar's locked-click handler.
export default function BacklinksPageGated() {
  return (
    <FeatureGate feature="backlinks">
      <BacklinksPage />
    </FeatureGate>
  );
}

function BacklinksPage() {
  const { brand } = useBrand();
  const { addTask, completeTask, failTask } = useBackgroundTasks();

  const [summary, setSummary] = useState<Summary | null>(null);
  const [backlinks, setBacklinks] = useState<Backlink[]>([]);
  const [topPages, setTopPages] = useState<TopPage[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pages, setPages] = useState(1);
  const [status, setStatus] = useState("all");
  const [sort, setSort] = useState("recent");
  const [domain, setDomain] = useState("");
  const [loading, setLoading] = useState(true);
  const [syncing, setSyncing] = useState(false);
  const [source, setSource] = useState<string | null>(null);
  const [lastSyncDate, setLastSyncDate] = useState<string | null>(null);
  const [tab, setTab] = useState<"backlinks" | "domains">("backlinks");
  const [refDomains, setRefDomains] = useState<Array<{ domain: string; rank: number; backlinks: number; firstSeen: string | null; lastSeen: string | null }>>([]);
  const [refLoading, setRefLoading] = useState(false);

  const loadSummary = useCallback(async () => {
    if (!brand?.id) return;
    const [summRes, snapRes] = await Promise.all([
      fetch(`/api/backlinks/summary?brandId=${brand.id}`),
      fetch(`/api/backlinks/snapshots?brandId=${brand.id}`),
    ]);
    if (summRes.ok) setSummary(await summRes.json());
    if (snapRes.ok) {
      const d = await snapRes.json();
      const snaps = d.snapshots || [];
      if (snaps.length > 0) setLastSyncDate(snaps[snaps.length - 1].snapshotDate);
    }
  }, [brand.id]);

  const loadBacklinks = useCallback(async () => {
    const params = new URLSearchParams({ brandId: brand.id, status, sort, page: String(page) });
    if (domain) params.set("domain", domain);
    const r = await fetch(`/api/backlinks?${params}`);
    if (r.ok) {
      const d = await r.json();
      setBacklinks(d.backlinks || []); setTotal(d.total || 0); setPages(d.pages || 1);
    }
  }, [brand.id, status, sort, page, domain]);

  const loadTopPages = useCallback(async () => {
    const r = await fetch(`/api/backlinks/top-pages?brandId=${brand.id}`);
    if (r.ok) { const d = await r.json(); setTopPages(d.pages || []); }
  }, [brand.id]);

  const loadRefDomains = useCallback(async () => {
    setRefLoading(true);
    try {
      const r = await fetch(`/api/backlinks/referring-domains?brandId=${brand.id}`);
      if (r.ok) { const d = await r.json(); setRefDomains(d.domains || []); if (d.source) setSource(d.source); }
    } finally { setRefLoading(false); }
  }, [brand.id]);

  useEffect(() => {
    setLoading(true);
    Promise.all([loadSummary(), loadBacklinks(), loadTopPages()]).finally(() => setLoading(false));
  }, [loadSummary, loadBacklinks, loadTopPages]);

  async function syncBacklinks() {
    setSyncing(true);
    const taskId = addTask({ id: `bl_sync_${Date.now()}`, type: "backlink_sync", label: "Syncing Backlinks...", brandId: brand.id, resultUrl: "/backlinks" });
    try {
      const r = await fetch("/api/backlinks/sync", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ brandId: brand.id }) });
      if (r.ok) { const d = await r.json(); setSource(d.source || null); completeTask(taskId, { resultUrl: "/backlinks", resultSummary: `Synced ${d.total} backlinks (${d.newCount} new, ${d.lostCount} lost) via ${d.source || "GSC"}` }); await Promise.all([loadSummary(), loadBacklinks(), loadTopPages()]); }
      else failTask(taskId, "Sync failed");
    } catch { failTask(taskId, "Network error"); }
    setSyncing(false);
  }

  function handleDisavow(ids: string[]) {
    setBacklinks((prev) => prev.map((b) => ids.includes(b.id) ? { ...b, status: "disavowed" } : b));
    loadSummary();
  }

  if (loading) return <div className="flex items-center justify-center h-64"><Loader2 className="w-8 h-8 animate-spin text-slate-300" /></div>;

  return (
    <div className="space-y-6 max-w-6xl">
      {/* Header */}
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Backlink Monitoring</h1>
          <p className="text-sm text-slate-500 mt-1">Track, analyze, and manage backlinks for {brand.domain}</p>
        </div>
        <div className="text-right">
          <button onClick={syncBacklinks} disabled={syncing} className="flex items-center gap-2 px-4 py-2 bg-slate-900 text-white text-sm font-semibold rounded-lg hover:bg-slate-800 disabled:opacity-50">
            {syncing ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />} {syncing ? "Syncing..." : "Sync Backlinks"}
          </button>
          <p className="text-xs text-slate-500 mt-1.5">
            Backlinks sync automatically every week.{lastSyncDate ? ` Last synced: ${new Date(lastSyncDate).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}.` : ""}
          </p>
        </div>
      </div>

      {/* Overview */}
      {summary && <OverviewCards data={summary} />}

      {/* Quality + Trend row */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {summary && <QualityChart distribution={summary.qualityDistribution || {}} />}
        <TrendChart brandId={brand.id} />
      </div>

      {/* Tab toggle */}
      <div className="flex bg-slate-100 rounded-lg p-0.5 w-fit">
        <button onClick={() => setTab("backlinks")} className={`px-4 py-1.5 text-xs font-semibold rounded-md transition-colors ${tab === "backlinks" ? "bg-white text-slate-900 shadow-sm" : "text-slate-500 hover:text-slate-700"}`}>All Backlinks</button>
        <button onClick={() => { setTab("domains"); if (refDomains.length === 0) loadRefDomains(); }} className={`px-4 py-1.5 text-xs font-semibold rounded-md transition-colors ${tab === "domains" ? "bg-white text-slate-900 shadow-sm" : "text-slate-500 hover:text-slate-700"}`}>Referring Domains</button>
      </div>

      {/* Referring Domains tab */}
      {tab === "domains" && (
        <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
          {refLoading ? (
            <div className="flex justify-center py-12"><Loader2 className="w-5 h-5 animate-spin text-slate-300" /></div>
          ) : refDomains.length === 0 ? (
            <div className="text-center py-12 text-xs text-slate-400">No referring domains found</div>
          ) : (
            <table className="w-full text-sm">
              <thead><tr className="border-b border-slate-100 bg-slate-50">
                <th className="text-left px-4 py-2.5 text-[10px] font-bold text-slate-500 uppercase">Domain</th>
                <th className="text-right px-3 py-2.5 text-[10px] font-bold text-slate-500 uppercase">Rank</th>
                <th className="text-right px-3 py-2.5 text-[10px] font-bold text-slate-500 uppercase">Backlinks</th>
                <th className="text-right px-3 py-2.5 text-[10px] font-bold text-slate-500 uppercase">First Seen</th>
                <th className="text-right px-3 py-2.5 text-[10px] font-bold text-slate-500 uppercase">Last Seen</th>
              </tr></thead>
              <tbody className="divide-y divide-slate-100">
                {refDomains.map((d, i) => (
                  <tr key={i} className="hover:bg-slate-50">
                    <td className="px-4 py-2.5 text-xs font-semibold text-slate-800">{d.domain}</td>
                    <td className="px-3 py-2.5 text-xs text-right text-slate-600">{d.rank}</td>
                    <td className="px-3 py-2.5 text-xs text-right font-semibold text-slate-800">{d.backlinks}</td>
                    <td className="px-3 py-2.5 text-xs text-right text-slate-400">{d.firstSeen ? new Date(d.firstSeen).toLocaleDateString() : "—"}</td>
                    <td className="px-3 py-2.5 text-xs text-right text-slate-400">{d.lastSeen ? new Date(d.lastSeen).toLocaleDateString() : "—"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      )}

      {/* Main backlinks tab — Gap Analysis leads the view because it's
          the outcome-driving section (which links should we go after
          next?), followed by Toxic Backlinks (which links should we
          disavow?), then Top Linked Pages for diagnostic context, and
          finally the full paginated table for drilling down. */}
      {tab === "backlinks" && (
        <>
      {/* Gap analysis — now lives at the top; it's the "what do we do
          next?" entry point and deserves the prime slot. */}
      <GapAnalysis brandId={brand.id} />

      {/* Toxic panel — lowered score threshold (≥ 40 = Moderate+) so
          the user sees the entire risk ladder, not just the absolute
          worst links. Health bar in the header shows the full bucket
          distribution across every active backlink. */}
      <ToxicPanel
        brandId={brand.id}
        links={backlinks
          .filter((b) => (b.toxicityScore ?? 0) >= 40 && b.status !== "disavowed")
          .map((b) => ({
            id: b.id,
            sourceDomain: b.sourceDomain,
            toxicityScore: b.toxicityScore,
            qualityTier: b.qualityTier,
            toxicityReasons: b.toxicityReasons,
          }))}
        health={summary?.health}
        onDisavow={handleDisavow}
        onRescored={() => { loadSummary(); loadBacklinks(); }}
      />

      {/* Top linked pages */}
      {topPages.length > 0 && (
        <div className="bg-white rounded-xl border border-slate-200 p-5">
          <h3 className="text-sm font-bold text-slate-800 mb-3 flex items-center gap-2"><Globe className="w-4 h-4 text-teal-600" /> Top Linked Pages</h3>
          <div className="space-y-2">
            {topPages.slice(0, 10).map((p, i) => (
              <div key={i} className="flex items-center gap-3 px-3 py-2 rounded-lg hover:bg-slate-50">
                <span className="text-xs font-mono text-slate-700 flex-1 truncate">{p.targetUrl.replace(/^https?:\/\/[^/]+/, "")}</span>
                <span className="text-xs text-slate-500">{p.backlinkCount} links</span>
                <span className="text-xs text-slate-500">{p.domainCount} domains</span>
                <span className="text-xs font-bold text-teal-600">DA {p.avgAuthority.toFixed(0)}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Main paginated table — last so the user can scroll to it for
          the full drill-down after reading the higher-level sections. */}
      <BacklinkTable backlinks={backlinks} total={total} page={page} pages={pages}
        onPageChange={(p) => setPage(p)} onStatusFilter={(s) => { setStatus(s); setPage(1); }}
        onSortChange={(s) => { setSort(s); setPage(1); }} onSearch={(d) => { setDomain(d); setPage(1); }}
        currentStatus={status} currentSort={sort} />
        </>
      )}

      {/* Empty state */}
      {!summary || summary.total === 0 ? (
        <div className="bg-white rounded-xl border border-slate-200 p-12 text-center">
          <Link2 className="w-10 h-10 text-slate-200 mx-auto mb-3" />
          <p className="text-sm font-semibold text-slate-700 mb-1">No Backlinks Yet</p>
          <p className="text-xs text-slate-500 mb-4">Sync your backlink data{source === "live" ? " from our SERP provider" : " from Google Search Console"}</p>
          <button onClick={syncBacklinks} disabled={syncing} className="px-4 py-2 bg-slate-900 text-white text-xs font-semibold rounded-lg hover:bg-slate-800 disabled:opacity-50">Sync Now</button>
        </div>
      ) : null}
    </div>
  );
}
