"use client";

import { useState } from "react";
import { ChevronDown, ChevronRight, Check, X, AlertTriangle, ExternalLink } from "lucide-react";
import type { AiSearchVerification } from "@/lib/audit/types";

interface Props {
  aiSearchVerification: AiSearchVerification | null | undefined;
}

// ─── Helpers ──────────────────────────────────────────────────────────────────

function pct(r: number): string {
  return `${Math.round(r * 100)}%`;
}

function mentionBg(rate: number): string {
  if (rate >= 0.6) return "bg-emerald-100 text-emerald-800";
  if (rate >= 0.3) return "bg-amber-100 text-amber-800";
  return "bg-rose-100 text-rose-800";
}

function MentionBadge({ rate, label }: { rate: number; label: string }) {
  return (
    <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold ${mentionBg(rate)}`}>
      {rate >= 0.6 ? <Check size={10} /> : rate >= 0.3 ? <AlertTriangle size={10} /> : <X size={10} />}
      {pct(rate)} {label}
    </span>
  );
}

// ─── Engine card ──────────────────────────────────────────────────────────────

function EngineCard({ summary }: { summary: AiSearchVerification["engineSummaries"][number] }) {
  const [open, setOpen] = useState(false);

  return (
    <div className="border border-slate-200 rounded-lg overflow-hidden">
      <button
        onClick={() => setOpen(!open)}
        className="w-full flex items-center justify-between p-4 text-left hover:bg-slate-50 transition-colors"
      >
        <div className="flex items-center gap-3">
          {open ? <ChevronDown size={14} className="text-slate-400 flex-shrink-0" /> : <ChevronRight size={14} className="text-slate-400 flex-shrink-0" />}
          <div>
            <div className="font-semibold text-sm text-slate-900">{summary.engineDisplayName}</div>
            <div className="text-xs text-slate-500">{summary.engineSubtitle}</div>
          </div>
        </div>
        <div className="flex items-center gap-2 flex-shrink-0">
          <MentionBadge rate={summary.brandMentionRate} label="mention" />
          {summary.successRate < 0.8 && (
            <span className="text-xs text-rose-500 font-medium">{pct(summary.successRate)} success</span>
          )}
        </div>
      </button>

      {open && (
        <div className="border-t border-slate-100 p-4 bg-slate-50 space-y-3">
          <div className="grid grid-cols-3 gap-3 text-center">
            <div className="bg-white rounded p-3 border border-slate-100">
              <div className="text-lg font-bold text-slate-900">{pct(summary.brandMentionRate)}</div>
              <div className="text-xs text-slate-500">Mention rate</div>
            </div>
            <div className="bg-white rounded p-3 border border-slate-100">
              <div className="text-lg font-bold text-slate-900">{pct(summary.brandCitationRate)}</div>
              <div className="text-xs text-slate-500">Citation rate</div>
            </div>
            <div className="bg-white rounded p-3 border border-slate-100">
              <div className="text-lg font-bold text-slate-900">
                {summary.avgPositionWhenMentioned !== null ? `#${summary.avgPositionWhenMentioned.toFixed(1)}` : "—"}
              </div>
              <div className="text-xs text-slate-500">Avg position</div>
            </div>
          </div>

          {summary.topCompetitorsMentioned.length > 0 && (
            <div>
              <div className="text-xs font-semibold text-slate-600 mb-1">Competitors appearing instead</div>
              <div className="flex flex-wrap gap-1">
                {summary.topCompetitorsMentioned.map((c) => (
                  <span key={c.name} className="text-xs px-2 py-0.5 bg-rose-50 text-rose-700 rounded-full">
                    {c.name} ({c.mentionCount}×)
                  </span>
                ))}
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

// ─── Citation domain row ──────────────────────────────────────────────────────

function CitationRow({ citation }: { citation: AiSearchVerification["topCitations"][number] }) {
  const badge = citation.isBrandDomain
    ? "bg-indigo-50 text-indigo-700"
    : citation.isCompetitorDomain
      ? "bg-rose-50 text-rose-700"
      : "bg-slate-50 text-slate-600";

  return (
    <div className="flex items-center justify-between py-2 border-b border-slate-50 last:border-0">
      <div className="flex items-center gap-2">
        <span className={`text-xs px-1.5 py-0.5 rounded font-medium ${badge}`}>
          {citation.isBrandDomain ? "brand" : citation.isCompetitorDomain ? "competitor" : "other"}
        </span>
        <span className="text-sm text-slate-700 font-mono">{citation.domain}</span>
      </div>
      <span className="text-xs text-slate-500 font-semibold">{citation.citationCount}×</span>
    </div>
  );
}

// ─── Query result row ─────────────────────────────────────────────────────────

function QueryResultCard({ result }: { result: AiSearchVerification["engineResults"][number] }) {
  const [imgError, setImgError] = useState(false);

  return (
    <div className="border border-slate-200 rounded-lg p-3 space-y-2">
      <div className="flex items-start justify-between gap-2">
        <div className="flex-1 min-w-0">
          <div className="text-xs font-medium text-slate-500 mb-0.5">{result.engineDisplayName}</div>
          <div className="text-sm text-slate-800 leading-snug">{result.query}</div>
        </div>
        <div className="flex items-center gap-1.5 flex-shrink-0">
          {result.brandMentioned ? (
            <span className="inline-flex items-center gap-0.5 text-xs px-1.5 py-0.5 bg-emerald-50 text-emerald-700 rounded-full font-medium">
              <Check size={9} /> Mentioned
            </span>
          ) : (
            <span className="inline-flex items-center gap-0.5 text-xs px-1.5 py-0.5 bg-rose-50 text-rose-600 rounded-full font-medium">
              <X size={9} /> Not found
            </span>
          )}
          {result.screenshotUrl && !imgError && (
            <a href={result.screenshotUrl} target="_blank" rel="noopener noreferrer" className="text-slate-400 hover:text-indigo-600">
              <ExternalLink size={12} />
            </a>
          )}
        </div>
      </div>

      {result.screenshotUrl && !imgError && (
        <img
          src={result.screenshotUrl}
          alt={`AI engine screenshot for: ${result.query}`}
          className="w-full rounded border border-slate-100 max-h-40 object-top object-cover"
          onError={() => setImgError(true)}
        />
      )}

      {result.competitorsMentioned.length > 0 && (
        <div className="flex flex-wrap gap-1">
          {result.competitorsMentioned.map((c) => (
            <span key={c} className="text-[10px] px-1.5 py-0.5 bg-rose-50 text-rose-700 rounded">
              {c}
            </span>
          ))}
        </div>
      )}
    </div>
  );
}

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

export function AiSearchVerificationSection({ aiSearchVerification }: Props) {
  const [showAllResults, setShowAllResults] = useState(false);

  if (!aiSearchVerification) return null;

  const asv = aiSearchVerification;
  const v = asv.brandVisibility;

  const visibleResults = showAllResults
    ? asv.engineResults
    : asv.engineResults.filter((r) => r.success).slice(0, 10);

  return (
    <section id="ai-search-verification" className="space-y-6">
      <div>
        <h2 className="text-xl font-bold text-slate-900">AI Search Engine Visibility</h2>
        <p className="text-sm text-slate-500 mt-0.5">
          Live verification across {asv.engineSummaries.length} AI search platforms —{" "}
          {asv.queriesChecked} queries checked
          {asv.degraded && (
            <span className="ml-2 text-amber-600 font-medium">
              <AlertTriangle size={12} className="inline mb-0.5" /> Partial results
            </span>
          )}
        </p>
      </div>

      {/* Overall visibility summary */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
        <div className="bg-white border border-slate-200 rounded-xl p-4 text-center">
          <div className={`text-3xl font-extrabold ${v.overallMentionRate >= 0.5 ? "text-emerald-600" : v.overallMentionRate >= 0.25 ? "text-amber-600" : "text-rose-600"}`}>
            {pct(v.overallMentionRate)}
          </div>
          <div className="text-xs text-slate-500 mt-1">Overall mention rate</div>
        </div>
        <div className="bg-white border border-slate-200 rounded-xl p-4 text-center">
          <div className="text-3xl font-extrabold text-indigo-600">{pct(v.overallCitationRate)}</div>
          <div className="text-xs text-slate-500 mt-1">Citation rate</div>
        </div>
        <div className="bg-white border border-slate-200 rounded-xl p-4 text-center">
          <div className={`text-3xl font-extrabold ${v.brandedQueryMentionRate >= 0.6 ? "text-emerald-600" : "text-amber-600"}`}>
            {pct(v.brandedQueryMentionRate)}
          </div>
          <div className="text-xs text-slate-500 mt-1">Branded queries</div>
        </div>
        <div className="bg-white border border-slate-200 rounded-xl p-4 text-center">
          <div className={`text-3xl font-extrabold ${v.nonBrandedMentionRate >= 0.3 ? "text-emerald-600" : "text-rose-600"}`}>
            {pct(v.nonBrandedMentionRate)}
          </div>
          <div className="text-xs text-slate-500 mt-1">Non-branded queries</div>
        </div>
      </div>

      {/* Query type breakdown */}
      <div className="bg-white border border-slate-200 rounded-xl p-5 space-y-3">
        <h3 className="text-sm font-semibold text-slate-700">Visibility by query type</h3>
        {[
          { label: "Branded", rate: v.brandedQueryMentionRate },
          { label: "Non-branded national", rate: v.nonBrandedMentionRate },
          { label: "Local / geo-targeted", rate: v.localQueryMentionRate },
          { label: "Informational / long-tail", rate: v.informationalMentionRate },
        ].map(({ label, rate }) => (
          <div key={label} className="space-y-1">
            <div className="flex justify-between text-xs text-slate-600">
              <span>{label}</span>
              <span className="font-semibold">{pct(rate)}</span>
            </div>
            <div className="h-2 bg-slate-100 rounded-full overflow-hidden">
              <div
                className={`h-full rounded-full transition-all ${rate >= 0.5 ? "bg-emerald-500" : rate >= 0.25 ? "bg-amber-500" : "bg-rose-500"}`}
                style={{ width: `${Math.round(rate * 100)}%` }}
              />
            </div>
          </div>
        ))}
      </div>

      {/* Engine summaries */}
      <div className="space-y-2">
        <h3 className="text-sm font-semibold text-slate-700">Results by AI engine</h3>
        {asv.engineSummaries
          .sort((a, b) => b.brandMentionRate - a.brandMentionRate)
          .map((s) => (
            <EngineCard key={s.engineInternalName} summary={s} />
          ))}
      </div>

      {/* Top citations */}
      {asv.topCitations.length > 0 && (
        <div className="bg-white border border-slate-200 rounded-xl p-5">
          <h3 className="text-sm font-semibold text-slate-700 mb-3">Most-cited domains across AI engines</h3>
          <div className="divide-y divide-slate-50">
            {asv.topCitations.map((c) => (
              <CitationRow key={c.domain} citation={c} />
            ))}
          </div>
        </div>
      )}

      {/* Insights */}
      {asv.insights.length > 0 && (
        <div className="bg-indigo-50 border border-indigo-100 rounded-xl p-5 space-y-2">
          <h3 className="text-sm font-semibold text-indigo-800">Key findings</h3>
          <ul className="space-y-2">
            {asv.insights.map((ins, i) => (
              <li key={i} className="flex gap-2 text-sm text-indigo-900">
                <span className="text-indigo-400 font-bold flex-shrink-0">{i + 1}.</span>
                {ins}
              </li>
            ))}
          </ul>
        </div>
      )}

      {/* Query-level results */}
      <div className="space-y-3">
        <div className="flex items-center justify-between">
          <h3 className="text-sm font-semibold text-slate-700">Query-level results</h3>
          <button
            onClick={() => setShowAllResults(!showAllResults)}
            className="text-xs text-indigo-600 hover:text-indigo-800 font-medium"
          >
            {showAllResults ? "Show fewer" : `Show all ${asv.engineResults.length}`}
          </button>
        </div>
        <div className="grid gap-3 sm:grid-cols-2">
          {visibleResults.map((r, i) => (
            <QueryResultCard key={`${r.engineInternalName}-${r.query}-${i}`} result={r} />
          ))}
        </div>
      </div>

      {/* Patent relevance */}
      <div className="bg-slate-50 border border-slate-200 rounded-xl p-4 text-xs text-slate-500">
        <span className="font-semibold text-slate-600">meSEO AI Search Verification:</span>{" "}
        Live probes across all major AI search platforms using meSEO&apos;s proprietary query categorization engine.
        Results reflect real-time AI-generated responses and citation patterns, captured and analyzed without relying
        on historical index data.
      </div>
    </section>
  );
}
