"use client";

import { useState, useEffect, useCallback, useRef } from "react";

const CACHE_TTL_MS = 5 * 60 * 1000;
const auditPageCache = new Map<string, { data: AuditData; fetchedAt: number }>();
import { useBrand } from "@/context/brand-context";
import { useBackgroundTasks } from "@/lib/stores/task-store";
import { Hero }          from "./_sections/Hero";
import { StatsRow }      from "./_sections/StatsRow";
import { PriorityStack } from "./_sections/PriorityStack";
import { Matrix }        from "./_sections/Matrix";
import { Annotation }    from "./_sections/Annotation";
import { Behavioral }    from "./_sections/Behavioral";
import { SectionNoAudit, SectionDegradedMode } from "./_lib/empty-states";
import type {
  HeroViewModel,
  StatsViewModel,
  PriorityViewModel,
  MatrixViewModel,
  AnnotationViewModel,
  BehavioralViewModel,
} from "./_lib/types";

interface AuditData {
  auditId: string;
  createdAt: string;
  degradedMode: boolean;
  /** Crawl failure reason -- present only when degradedMode is true. */
  crawlErrorReason?: string;
  statsStatus: "complete" | "partial" | "updating";
  siteTagInstalled?: boolean;
  heroVm: HeroViewModel;
  statsVm: StatsViewModel;
  priorityVm: PriorityViewModel;
  matrixVm: MatrixViewModel;
  annotationVm: AnnotationViewModel;
  behavioralVm: BehavioralViewModel;
}

function SectionHeader({ icon, title, subtitle }: { icon: React.ReactNode; title: string; subtitle?: string }) {
  return (
    <div className="flex items-baseline justify-between gap-4 mt-8 mb-3.5">
      <h2 className="text-[18px] font-bold text-slate-900 tracking-tight flex items-center gap-2">
        <span className="text-red-500 w-4.5 h-4.5">{icon}</span>
        {title}
      </h2>
      {subtitle && <span className="text-[12px] text-slate-500 shrink-0">{subtitle}</span>}
    </div>
  );
}

export default function TechnicalAuditPage() {
  const { brand, siteTagInstalled, siteTagResolvedForBrandId } = useBrand();
  const [triggering, setTriggering] = useState(false);
  const [notice, setNotice] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const [data, setData] = useState<AuditData | null>(null);
  const [loading, setLoading] = useState(true);
  const [fetchError, setFetchError] = useState(false);
  // ID of the in-flight SEO audit being polled for completion.
  const [runningAuditId, setRunningAuditId] = useState<string | null>(null);
  const [auditProgress, setAuditProgress] = useState<string | null>(null);
  const runningRef = useRef<string | null>(null);
  const bgTaskRef = useRef<string | null>(null);
  const { addTask, completeTask, failTask } = useBackgroundTasks();

  const fetchLatest = useCallback(async () => {
    if (!brand.id) return;
    const cached = auditPageCache.get(brand.id);
    if (cached && Date.now() - cached.fetchedAt < CACHE_TTL_MS) {
      setData(cached.data);
      setLoading(false);
      // Revalidate in background without blocking
      fetch(`/api/brands/${brand.id}/seo-audit/latest`)
        .then((r) => r.json())
        .then((json: AuditData | null) => {
          if (json) {
            auditPageCache.set(brand.id, { data: json, fetchedAt: Date.now() });
            setData(json);
          }
        })
        .catch(() => {});
      return;
    }
    setLoading(true);
    setFetchError(false);
    try {
      const r = await fetch(`/api/brands/${brand.id}/seo-audit/latest`);
      const json: AuditData | null = await r.json();
      if (json) auditPageCache.set(brand.id, { data: json, fetchedAt: Date.now() });
      setData(json);
    } catch {
      setFetchError(true);
    } finally {
      setLoading(false);
    }
  }, [brand.id]);

  const refreshStats = useCallback(async () => {
    if (!brand.id || !data) return;
    try {
      const r = await fetch(`/api/brands/${brand.id}/seo-audit/latest/stats`);
      const json: { statsVm: StatsViewModel; statsStatus: string } | null = await r.json();
      if (!json) return;
      setData((prev) => {
        if (!prev) return prev;
        const next = {
          ...prev,
          statsVm: json.statsVm,
          statsStatus: json.statsStatus as AuditData["statsStatus"],
        };
        auditPageCache.set(brand.id, { data: next, fetchedAt: Date.now() });
        return next;
      });
    } catch {
      // silently ignore refresh failures
    }
  }, [brand.id, data]);

  useEffect(() => { fetchLatest(); }, [fetchLatest]);

  // Poll the running audit for completion. Fires whenever runningAuditId is set.
  useEffect(() => {
    if (!runningAuditId) return;
    runningRef.current = runningAuditId;

    const interval = setInterval(async () => {
      if (!runningRef.current) return;
      try {
        const res = await fetch(`/api/admin/audits/${runningRef.current}/status`);
        if (!res.ok) return;
        const d = await res.json() as { status: string; progressLabel?: string };
        if (d.progressLabel) setAuditProgress(d.progressLabel);
        if (d.status === "completed") {
          clearInterval(interval);
          setRunningAuditId(null);
          setAuditProgress(null);
          runningRef.current = null;
          if (bgTaskRef.current) {
            completeTask(bgTaskRef.current, { resultUrl: "/technical-audit", resultSummary: `Technical audit complete for ${brand.name}` });
            bgTaskRef.current = null;
          }
          setNotice({ type: "success", text: "Audit complete. Loading fresh results..." });
          await fetchLatest();
          setNotice({ type: "success", text: "Audit complete. Results updated." });
          // Write in-app notification so the bell surfaces it if user navigated away
          fetch(`/api/brands/${brand.id}/seo-audit/notify-complete`, { method: "POST" }).catch(() => {});
        } else if (d.status === "failed") {
          clearInterval(interval);
          setRunningAuditId(null);
          setAuditProgress(null);
          runningRef.current = null;
          if (bgTaskRef.current) {
            failTask(bgTaskRef.current, "Audit failed");
            bgTaskRef.current = null;
          }
          setNotice({ type: "error", text: "Audit failed. Please try again." });
        }
      } catch {
        // silently retry
      }
    }, 3000);

    return () => { clearInterval(interval); };
  }, [runningAuditId, fetchLatest, brand.id]);

  async function triggerAudit() {
    if (triggering) return;
    setTriggering(true);
    setNotice(null);
    try {
      const res = await fetch("/api/admin/audits/trigger", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ website: brand.domain, brandId: brand.id }),
      });
      if (res.status === 403) {
        setNotice({ type: "error", text: "Admin access required to trigger audits." });
      } else if (!res.ok) {
        const json = await res.json().catch(() => ({}));
        setNotice({ type: "error", text: `Audit trigger failed: ${(json as { error?: string }).error ?? res.statusText}` });
      } else {
        const json = await res.json().catch(() => ({})) as { auditId?: string };
        if (json.auditId) {
          setRunningAuditId(json.auditId);
          bgTaskRef.current = addTask({
            id: `seo_audit_${json.auditId}`,
            type: "technical_audit",
            label: `Running Technical Audit for ${brand.name}`,
            brandId: brand.id,
            resultUrl: "/technical-audit",
          });
          setNotice({ type: "success", text: "Audit started. Updating automatically when complete..." });
        } else {
          setNotice({ type: "success", text: "Audit started. Refresh in 60-90 seconds." });
        }
      }
    } catch {
      setNotice({ type: "error", text: "Audit trigger failed: network error." });
    } finally {
      setTriggering(false);
    }
  }

  return (
    <div className="space-y-6 max-w-[1440px] pb-20">

      {/* Page title */}
      <div className="flex items-start justify-between gap-6">
        <div>
          <h1 className="text-[26px] font-bold text-slate-900 tracking-tight leading-tight">
            Technical Audit
          </h1>
          <p className="text-[13px] text-slate-500 mt-1">
            Audited on{" "}
            <span className="text-slate-600">{brand.domain}</span>
          </p>
        </div>
        <div className="flex flex-col items-end gap-2 shrink-0">
          <div className="flex items-center gap-2.5">
            <button
              onClick={triggerAudit}
              disabled={triggering || !!runningAuditId}
              className="inline-flex items-center gap-1.5 px-4 py-2.5 bg-white border border-slate-200 text-[13px] font-medium text-slate-700 rounded-lg hover:bg-slate-50 hover:border-slate-300 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth={1.5}>
                <circle cx="7" cy="7" r="5.5" />
                <circle cx="7" cy="7" r="2" fill="currentColor" />
              </svg>
              {triggering ? "Starting..." : runningAuditId ? "Running..." : "Live Audit"}
            </button>
            <button
              onClick={triggerAudit}
              disabled={triggering || !!runningAuditId}
              className="inline-flex items-center gap-1.5 px-4 py-2.5 bg-red-500 text-white text-[13px] font-medium rounded-lg hover:bg-red-600 transition-colors disabled:opacity-60 disabled:cursor-not-allowed"
            >
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round">
                <path d="M7 2v3.5M7 2L5 4m2-2l2 2M2 7h10M4 10.5l-2 2M10 10.5l2 2M7 12V8.5" />
              </svg>
              {triggering ? "Starting..." : runningAuditId ? "Running..." : "Re-run Audit"}
            </button>
          </div>
          {notice && (
            <p className={`text-[12px] font-medium ${notice.type === "success" ? "text-emerald-600" : "text-red-600"}`}>
              {notice.text}
            </p>
          )}
          {auditProgress && (
            <p className="text-[11px] text-slate-400">{auditProgress}</p>
          )}
        </div>
      </div>

      {/* Site Tag callout -- only shown once the CURRENT brand's /api/site-tag has resolved
          AND the tag is confirmed not installed. siteTagResolvedForBrandId tracks the brand
          whose status is in siteTagInstalled, so the banner cannot render during initial load
          or mid-switch (when siteTagInstalled still holds the previous brand's value). */}
      {siteTagResolvedForBrandId === brand.id && siteTagInstalled === false && <div className="flex items-center gap-3 bg-white border border-slate-200 rounded-xl px-4 py-3 text-[13px] shadow-subtle">
        <svg className="w-4 h-4 text-slate-400 shrink-0" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth={1.5}>
          <circle cx="8" cy="8" r="6.5" />
          <circle cx="8" cy="8" r="2" fill="currentColor" />
        </svg>
        <span className="text-slate-600 flex-1">
          Install the meSEO Site Tag to highlight issues directly on your live site.
        </span>
        <button className="text-red-500 font-medium hover:text-red-600 transition-colors flex items-center gap-1">
          Install Site Tag
          <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round">
            <path d="M2 5.5h7M6 3l3 2.5L6 8" />
          </svg>
        </button>
      </div>}

      {/* Loading */}
      {loading && (
        <div className="flex items-center gap-4 bg-white border border-slate-200 rounded-xl px-6 py-8 shadow-subtle">
          <svg className="w-5 h-5 text-slate-400 animate-spin shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
            <path d="M21 12a9 9 0 11-6.219-8.56" strokeLinecap="round" />
          </svg>
          <div>
            <p className="text-[14px] font-semibold text-slate-700">Analyzing your site</p>
            <p className="text-[12px] text-slate-400 mt-0.5">Loading audit results and live event counts...</p>
          </div>
        </div>
      )}

      {/* Fetch error */}
      {!loading && fetchError && (
        <div className="flex items-center gap-3 bg-red-50 border border-red-200 rounded-xl px-4 py-3 text-[13px] text-red-700">
          Failed to load audit data. Refresh the page to try again.
        </div>
      )}

      {/* No audit yet */}
      {!loading && !fetchError && !data && (
        <SectionNoAudit brandName={brand.name} />
      )}

      {/* Audit data */}
      {!loading && !fetchError && data && (
        <>
          {/* Degraded mode banner */}
          {data.degradedMode && <SectionDegradedMode crawlErrorReason={data.crawlErrorReason} />}

          {/* Hero */}
          <Hero vm={data.heroVm} />

          {/* Stats row */}
          <StatsRow stats={data.statsVm} statsStatus={data.statsStatus} onRefreshStats={refreshStats} />

          {/* Priority Action Stack */}
          <SectionHeader
            icon={
              <svg viewBox="0 0 18 18" fill="currentColor" className="w-[18px] h-[18px]">
                <path d="M9 1L11 6H16L12 9.5L13.5 15L9 12L4.5 15L6 9.5L2 6H7L9 1Z" />
              </svg>
            }
            title="Priority Action Stack"
            subtitle="AI-prioritized by impact x traffic x conversion proximity"
          />
          <PriorityStack priorities={data.priorityVm.items} />

          {/* Cross-Dimension Matrix */}
          <SectionHeader
            icon={
              <svg viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth={1.5} className="w-[18px] h-[18px]">
                <rect x="2" y="2" width="6" height="6" rx="1" />
                <rect x="10" y="2" width="6" height="6" rx="1" />
                <rect x="2" y="10" width="6" height="6" rx="1" />
                <rect x="10" y="10" width="6" height="6" rx="1" />
              </svg>
            }
            title="Cross-Dimension Page Matrix"
            subtitle="All audit dimensions synthesized per page"
          />
          <Matrix rows={data.matrixVm.rows} />

          {/* Visual Annotation */}
          <SectionHeader
            icon={
              <svg viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth={1.5} className="w-[18px] h-[18px]">
                <circle cx="9" cy="9" r="7" />
                <circle cx="9" cy="9" r="2.5" fill="currentColor" />
              </svg>
            }
            title="Visual Annotation"
            subtitle="Findings rendered in-context on the live page"
          />
          <Annotation annotation={data.annotationVm} isSiteTagInstalled={siteTagInstalled} />

          {/* Real-User Impact */}
          <SectionHeader
            icon={
              <svg viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth={1.5} className="w-[18px] h-[18px]">
                <polyline points="2,14 6,8 10,11 14,4 16,6" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            }
            title="Real-User Impact"
            subtitle="Powered by Site Tag behavioral data, last 7 days"
          />
          <Behavioral behavioral={data.behavioralVm} isSiteTagInstalled={siteTagInstalled} />

        </>
      )}

    </div>
  );
}
