"use client";

import { useState } from "react";
import { Eye, AlertTriangle, CheckCircle, ChevronDown, ChevronRight } from "lucide-react";
import type { LiveVisualAnnotations, PerPageAnnotation, AnnotationSpec } from "@/lib/audit/types";

interface Props {
  liveVisualAnnotations: LiveVisualAnnotations | null | undefined;
}

// ─── Severity helpers ─────────────────────────────────────────────────────────

function severityBadge(s: AnnotationSpec["severity"]): string {
  const map = {
    critical: "bg-red-100 text-red-700 border-red-200",
    high: "bg-orange-100 text-orange-700 border-orange-200",
    moderate: "bg-amber-100 text-amber-700 border-amber-200",
    low: "bg-slate-100 text-slate-600 border-slate-200",
    positive: "bg-emerald-100 text-emerald-700 border-emerald-200",
  } as const;
  return map[s];
}

function severityDot(s: AnnotationSpec["severity"]): string {
  const map = {
    critical: "bg-red-500",
    high: "bg-orange-500",
    moderate: "bg-amber-500",
    low: "bg-slate-400",
    positive: "bg-emerald-500",
  } as const;
  return map[s];
}

// ─── Aggregate stats strip ────────────────────────────────────────────────────

function StatsStrip({ lva }: { lva: LiveVisualAnnotations }) {
  const agg = lva.aggregateInsights;
  const total = agg.totalAnnotations;
  const allAnnotations = lva.perPageAnnotations.flatMap((p) => p.annotations);
  const critical = allAnnotations.filter((a) => a.severity === "critical").length;
  const high = allAnnotations.filter((a) => a.severity === "high").length;
  const moderate = allAnnotations.filter((a) => a.severity === "moderate").length;
  const positive = allAnnotations.filter((a) => a.severity === "positive").length;

  return (
    <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
      {[
        { label: "Critical", count: critical, color: "text-red-600 bg-red-50 border-red-200" },
        { label: "High", count: high, color: "text-orange-600 bg-orange-50 border-orange-200" },
        { label: "Moderate", count: moderate, color: "text-amber-600 bg-amber-50 border-amber-200" },
        { label: "Positive", count: positive, color: "text-emerald-600 bg-emerald-50 border-emerald-200" },
      ].map(({ label, count, color }) => (
        <div key={label} className={`border rounded-xl p-4 text-center ${color}`}>
          <div className="text-2xl font-extrabold">{count}</div>
          <div className="text-xs font-medium mt-0.5">{label}</div>
        </div>
      ))}
    </div>
  );
}

// ─── Top priority annotations ─────────────────────────────────────────────────

function TopPriorityAnnotations({ lva }: { lva: LiveVisualAnnotations }) {
  const top = lva.aggregateInsights.topPriorityAnnotations;
  if (top.length === 0) return null;

  return (
    <div className="space-y-2">
      <h3 className="text-sm font-semibold text-slate-700">Top Priority Issues</h3>
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
        {top.map((ann, i) => (
          <div key={i} className="border border-slate-200 rounded-xl p-4 space-y-1.5">
            <div className="flex items-center gap-2">
              <span className={`text-xs px-2 py-0.5 rounded-full font-semibold border ${severityBadge(ann.severity as AnnotationSpec["severity"])}`}>
                {ann.severity}
              </span>
              <span className="text-xs text-slate-400 truncate">{ann.pageUrl.replace(/^https?:\/\//, "").slice(0, 40)}</span>
            </div>
            <div className="text-sm font-semibold text-slate-800">{ann.shortLabel}</div>
            <div className="text-xs text-slate-500 leading-snug line-clamp-2">{ann.description}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Annotation row ───────────────────────────────────────────────────────────

function AnnotationRow({ ann }: { ann: AnnotationSpec }) {
  return (
    <tr className="border-b border-slate-100 last:border-0">
      <td className="px-3 py-2.5">
        <span className="inline-flex items-center justify-center w-5 h-5 rounded-full text-white text-xs font-bold" style={{ backgroundColor: ann.color }}>
          {ann.number}
        </span>
      </td>
      <td className="px-3 py-2.5">
        <span className={`text-xs px-1.5 py-0.5 rounded-full font-medium border ${severityBadge(ann.severity)}`}>
          {ann.severity}
        </span>
      </td>
      <td className="px-3 py-2.5 font-medium text-sm text-slate-800">{ann.shortLabel}</td>
      <td className="px-3 py-2.5 text-xs text-slate-500 max-w-xs">{ann.description}</td>
      <td className="px-3 py-2.5 text-xs text-slate-600">{ann.linkedAction}</td>
    </tr>
  );
}

// ─── Per-page display ─────────────────────────────────────────────────────────

function PagePanel({ page }: { page: PerPageAnnotation }) {
  const [showMobile, setShowMobile] = useState(false);

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-3 flex-wrap">
        <span className="text-xs text-slate-400">{page.pageUrl}</span>
        <div className="flex items-center gap-3 ml-auto">
          <button
            onClick={() => setShowMobile(!showMobile)}
            className="text-xs text-slate-500 hover:text-slate-800 transition-colors"
          >
            {showMobile ? "Hide" : "Show"} mobile view
          </button>
        </div>
      </div>

      <div className={`grid gap-4 ${showMobile ? "grid-cols-2" : "grid-cols-1"}`}>
        <div>
          <div className="text-xs font-semibold text-slate-500 mb-1.5">Desktop — Annotated</div>
          <a href={page.desktopAnnotatedScreenshotUrl} target="_blank" rel="noopener noreferrer">
            <img
              src={page.desktopAnnotatedScreenshotUrl}
              alt={`Annotated desktop screenshot of ${page.pageLabel}`}
              className="w-full rounded-xl border border-slate-200 hover:shadow-lg transition-shadow"
            />
          </a>
        </div>
        {showMobile && (
          <div>
            <div className="text-xs font-semibold text-slate-500 mb-1.5">Mobile View</div>
            <a href={page.mobileScreenshotUrl} target="_blank" rel="noopener noreferrer">
              <img
                src={page.mobileScreenshotUrl}
                alt={`Mobile screenshot of ${page.pageLabel}`}
                className="w-full rounded-xl border border-slate-200"
              />
            </a>
          </div>
        )}
      </div>

      {page.annotations.length > 0 && (
        <div className="border border-slate-200 rounded-xl overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-slate-50 border-b border-slate-100">
              <tr>
                <th className="px-3 py-2 text-left text-xs font-semibold text-slate-500">#</th>
                <th className="px-3 py-2 text-left text-xs font-semibold text-slate-500">Severity</th>
                <th className="px-3 py-2 text-left text-xs font-semibold text-slate-500">Issue</th>
                <th className="px-3 py-2 text-left text-xs font-semibold text-slate-500">Details</th>
                <th className="px-3 py-2 text-left text-xs font-semibold text-slate-500">Action</th>
              </tr>
            </thead>
            <tbody>
              {page.annotations.map((ann, i) => (
                <AnnotationRow key={i} ann={ann} />
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

// ─── Main section ─────────────────────────────────────────────────────────────

export function LiveVisualAnnotationsSection({ liveVisualAnnotations }: Props) {
  const [activeTab, setActiveTab] = useState(0);
  const [statsOpen, setStatsOpen] = useState(true);

  if (!liveVisualAnnotations?.hasAnnotations) return null;

  const lva = liveVisualAnnotations;
  const captureDate = new Date(lva.windowDate).toLocaleDateString("en-US", {
    month: "short", day: "numeric", year: "numeric",
  });

  return (
    <section id="audit-visual-analysis" className="space-y-5">
      {/* Header */}
      <div className="flex items-start justify-between gap-3">
        <div>
          <div className="flex items-center gap-2 mb-1">
            <Eye size={18} className="text-indigo-600" />
            <h2 className="text-xl font-bold text-slate-900">Live Site Visual Analysis</h2>
          </div>
          <p className="text-sm text-slate-500">
            {lva.perPageAnnotations.length} page{lva.perPageAnnotations.length !== 1 ? "s" : ""} captured
            with {lva.aggregateInsights.totalAnnotations} annotations highlighting visible issues — {captureDate}
          </p>
        </div>
        {lva.aggregateInsights.pagesWithCriticalIssues > 0 && (
          <div className="flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-red-50 border border-red-200 text-xs font-semibold text-red-700 flex-shrink-0">
            <AlertTriangle size={10} />
            {lva.aggregateInsights.pagesWithCriticalIssues} page{lva.aggregateInsights.pagesWithCriticalIssues !== 1 ? "s" : ""} with critical issues
          </div>
        )}
      </div>

      {/* Stats strip */}
      <div className="border border-slate-200 rounded-xl overflow-hidden">
        <button
          onClick={() => setStatsOpen(!statsOpen)}
          className="w-full flex items-center justify-between px-4 py-3 bg-slate-50 hover:bg-slate-100 transition-colors"
        >
          <span className="text-sm font-semibold text-slate-700">Annotation Summary</span>
          {statsOpen ? <ChevronDown size={14} className="text-slate-400" /> : <ChevronRight size={14} className="text-slate-400" />}
        </button>
        {statsOpen && (
          <div className="p-4">
            <StatsStrip lva={lva} />
          </div>
        )}
      </div>

      {/* Top priority issues */}
      <TopPriorityAnnotations lva={lva} />

      {/* Page tabs */}
      {lva.perPageAnnotations.length > 1 && (
        <div className="flex gap-2 border-b border-slate-200">
          {lva.perPageAnnotations.map((page, i) => (
            <button
              key={i}
              onClick={() => setActiveTab(i)}
              className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
                activeTab === i
                  ? "border-indigo-500 text-indigo-700"
                  : "border-transparent text-slate-500 hover:text-slate-700"
              }`}
            >
              {page.pageLabel}
              {page.severityBreakdown.critical > 0 && (
                <span className="ml-1.5 inline-block w-1.5 h-1.5 rounded-full bg-red-500" />
              )}
            </button>
          ))}
        </div>
      )}

      {/* Active page content */}
      {lva.perPageAnnotations[activeTab] && (
        <PagePanel page={lva.perPageAnnotations[activeTab]!} />
      )}

      {/* Strongest/weakest callouts */}
      {(lva.aggregateInsights.strongestPage || lva.aggregateInsights.weakestPage) && (
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
          {lva.aggregateInsights.strongestPage && (
            <div className="border border-emerald-200 bg-emerald-50 rounded-xl p-4">
              <div className="flex items-center gap-1.5 mb-1">
                <CheckCircle size={12} className="text-emerald-600" />
                <span className="text-xs font-semibold text-emerald-700">Strongest Composition</span>
              </div>
              <div className="text-sm font-medium text-slate-800">{lva.aggregateInsights.strongestPage.label}</div>
              <div className="text-xs text-slate-500">{lva.aggregateInsights.strongestPage.positiveAnnotationCount} positive signal{lva.aggregateInsights.strongestPage.positiveAnnotationCount !== 1 ? "s" : ""} detected</div>
            </div>
          )}
          {lva.aggregateInsights.weakestPage && (
            <div className="border border-red-200 bg-red-50 rounded-xl p-4">
              <div className="flex items-center gap-1.5 mb-1">
                <AlertTriangle size={12} className="text-red-600" />
                <span className="text-xs font-semibold text-red-700">Needs Most Attention</span>
              </div>
              <div className="text-sm font-medium text-slate-800">{lva.aggregateInsights.weakestPage.label}</div>
              <div className="text-xs text-slate-500">
                {lva.aggregateInsights.weakestPage.criticalCount} critical + {lva.aggregateInsights.weakestPage.highCount} high-severity issues
              </div>
            </div>
          )}
        </div>
      )}

      {/* Patent relevance */}
      <p className="text-xs text-slate-400 italic">{lva.patentRelevance}</p>
    </section>
  );
}
