"use client";

import { useState } from "react";
import type { SnippetCaptureStrategy, CapturedSnippetReformulation, SnippetType } from "@/lib/snippet-capture/types";

interface Props {
  snippetCaptureStrategy: SnippetCaptureStrategy | null | undefined;
}

const SNIPPET_TYPE_LABELS: Record<SnippetType, string> = {
  paragraph: "Paragraph",
  list_ordered: "Ordered List",
  list_unordered: "Unordered List",
  table: "Table",
  definition: "Definition",
  how_to: "How-To",
  faq: "FAQ",
  video: "Video",
};

const PROBABILITY_CONFIG = {
  high: { label: "High", class: "bg-emerald-500/20 text-emerald-400 border border-emerald-500/30" },
  moderate: { label: "Moderate", class: "bg-amber-500/20 text-amber-400 border border-amber-500/30" },
  low: { label: "Low", class: "bg-red-500/20 text-red-400 border border-red-500/30" },
} as const;

const TYPE_BADGE_CLASS = "bg-blue-500/20 text-blue-400 border border-blue-500/30";

function formatCurrency(n: number): string {
  if (n >= 1000) return `$${(n / 1000).toFixed(1)}k`;
  return `$${n}`;
}

function ReformulationCard({ r, index, expanded: defaultExpanded }: { r: CapturedSnippetReformulation; index: number; expanded?: boolean }) {
  const [open, setOpen] = useState(defaultExpanded ?? false);
  const probCfg = PROBABILITY_CONFIG[r.captureSpec.estimatedCaptureProbability];

  return (
    <div className="rounded-xl bg-slate-900/60 border border-white/10 overflow-hidden">
      {/* Header row -- always visible */}
      <button
        className="w-full text-left px-5 py-4 flex items-start gap-4 hover:bg-slate-800/40 transition-colors"
        onClick={() => setOpen((v) => !v)}
        aria-expanded={open}
      >
        <span className="shrink-0 w-6 h-6 rounded-full bg-slate-700 text-slate-300 text-xs font-bold flex items-center justify-center mt-0.5">
          {index + 1}
        </span>
        <div className="flex-1 min-w-0">
          <p className="text-sm font-semibold text-slate-100 leading-snug">{r.query}</p>
          <div className="flex flex-wrap items-center gap-2 mt-2">
            <span className={`text-xs font-medium px-2 py-0.5 rounded-full ${TYPE_BADGE_CLASS}`}>
              {SNIPPET_TYPE_LABELS[r.snippetType]}
            </span>
            <span className={`text-xs font-medium px-2 py-0.5 rounded-full ${probCfg.class}`}>
              {probCfg.label} probability
            </span>
            <span className="text-xs text-slate-400">
              {formatCurrency(r.estimatedMonthlyRevenueGain)}/mo revenue
            </span>
            <span className="text-xs text-slate-500">
              {r.estimatedMonthlyTrafficGain} sessions/mo
            </span>
          </div>
        </div>
        <span className="shrink-0 text-slate-500 text-sm mt-1">{open ? "▲" : "▼"}</span>
      </button>

      {open && (
        <div className="border-t border-white/5 px-5 py-4 space-y-4">
          {/* Target page */}
          <div className="rounded-lg bg-slate-800/60 border border-slate-700/40 px-4 py-3">
            {r.newPageRecommended ? (
              <p className="text-sm text-slate-300">
                <span className="text-amber-400 font-medium">New page recommended: </span>
                <code className="text-amber-300">/{r.newPageSlug}</code>
              </p>
            ) : (
              <p className="text-sm text-slate-300">
                <span className="text-emerald-400 font-medium">Existing page: </span>
                <span className="text-slate-300 break-all">{r.targetPageUrl ?? "Existing matching page"}</span>
              </p>
            )}
          </div>

          {/* Two-column body: spec left, skeleton right */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Left: capture spec */}
            <div className="space-y-3">
              <h4 className="text-xs font-semibold text-slate-400 uppercase tracking-wider">Capture Spec</h4>
              <div className="space-y-2 text-sm">
                <div className="flex gap-2">
                  <span className="text-slate-500 shrink-0 w-28">Word count</span>
                  <span className="text-slate-200 font-medium">{r.captureSpec.wordCountTarget.min}-{r.captureSpec.wordCountTarget.max}</span>
                </div>
                <div className="flex gap-2">
                  <span className="text-slate-500 shrink-0 w-28">Structure</span>
                  <span className="text-slate-300 leading-relaxed">{r.captureSpec.paragraphStructure}</span>
                </div>
                <div className="flex gap-2">
                  <span className="text-slate-500 shrink-0 w-28">Header</span>
                  <span className="text-slate-300 leading-relaxed">{r.captureSpec.headerFormat}</span>
                </div>
              </div>

              {/* Schema requirements */}
              {r.captureSpec.schemaRequirements.length > 0 && (
                <div className="space-y-2">
                  <h5 className="text-xs font-semibold text-slate-400 uppercase tracking-wider">Schema Requirements</h5>
                  {r.captureSpec.schemaRequirements.map((req, i) => (
                    <div key={i} className="rounded-lg bg-slate-800/40 border border-slate-700/30 p-3 space-y-1">
                      <div className="flex items-center gap-2">
                        <code className="text-xs font-bold text-violet-400 bg-violet-500/10 px-2 py-0.5 rounded">{req.schemaType}</code>
                      </div>
                      <p className="text-xs text-slate-400 leading-relaxed">{req.rationale}</p>
                      <div className="flex flex-wrap gap-1 mt-1">
                        {req.requiredProperties.map((p) => (
                          <code key={p} className="text-xs text-emerald-400 bg-emerald-500/10 px-1.5 py-0.5 rounded">{p}</code>
                        ))}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* Right: content skeleton */}
            <div className="space-y-3">
              <h4 className="text-xs font-semibold text-slate-400 uppercase tracking-wider">Content Skeleton <span className="text-slate-600 normal-case font-normal">(structural reference, not finished copy)</span></h4>
              <blockquote className="rounded-lg bg-slate-800/80 border-l-2 border-blue-500/60 px-4 py-3">
                <p className="text-sm text-slate-300 leading-relaxed italic">{r.captureSpec.contentSkeleton}</p>
              </blockquote>

              {r.captureSpec.competitorReference && (
                <div className="rounded-lg bg-slate-800/40 border border-slate-700/30 p-3">
                  <p className="text-xs text-slate-400 leading-relaxed">
                    <span className="text-slate-300 font-medium">Current landscape: </span>
                    {r.captureSpec.competitorReference}
                  </p>
                </div>
              )}

              <div className="rounded-lg bg-slate-800/40 border border-slate-700/30 p-3">
                <p className="text-xs text-slate-400 leading-relaxed">
                  <span className="text-slate-300 font-medium">Rationale: </span>
                  {r.captureSpec.captureRationale}
                </p>
              </div>
            </div>
          </div>

          {/* Footer: metrics */}
          <div className="flex flex-wrap gap-4 border-t border-white/5 pt-3 text-xs text-slate-400">
            <span>Monthly traffic gain: <strong className="text-slate-200">{r.estimatedMonthlyTrafficGain} sessions</strong></span>
            <span>Monthly revenue gain: <strong className="text-emerald-400">{formatCurrency(r.estimatedMonthlyRevenueGain)}</strong></span>
            <span>Capture probability: <strong className={probCfg.label === "High" ? "text-emerald-400" : probCfg.label === "Moderate" ? "text-amber-400" : "text-red-400"}>{probCfg.label}</strong></span>
          </div>
        </div>
      )}
    </div>
  );
}

function CompactReformulationRow({ r, index }: { r: CapturedSnippetReformulation; index: number }) {
  const [open, setOpen] = useState(false);
  const probCfg = PROBABILITY_CONFIG[r.captureSpec.estimatedCaptureProbability];

  return (
    <div className="rounded-lg bg-slate-900/40 border border-white/10 overflow-hidden">
      <button
        className="w-full text-left px-4 py-3 flex items-center gap-3 hover:bg-slate-800/40 transition-colors"
        onClick={() => setOpen((v) => !v)}
      >
        <span className="flex-1 text-sm text-slate-300 truncate">{r.query}</span>
        <span className={`shrink-0 text-xs font-medium px-2 py-0.5 rounded-full ${TYPE_BADGE_CLASS}`}>
          {SNIPPET_TYPE_LABELS[r.snippetType]}
        </span>
        <span className={`shrink-0 text-xs font-medium px-2 py-0.5 rounded-full ${probCfg.class}`}>
          {probCfg.label}
        </span>
        <span className="shrink-0 text-xs text-emerald-400 font-medium">{formatCurrency(r.estimatedMonthlyRevenueGain)}/mo</span>
        <span className="shrink-0 text-slate-500 text-xs">{open ? "▲" : "▼"}</span>
      </button>
      {open && (
        <div className="border-t border-white/5 px-4 py-3">
          <ReformulationCard r={r} index={index} expanded={true} />
        </div>
      )}
    </div>
  );
}

export function SnippetCaptureStrategySection({ snippetCaptureStrategy }: Props) {
  if (!snippetCaptureStrategy?.hasStrategy || snippetCaptureStrategy.totalReformulationsGenerated === 0) {
    return null;
  }

  const {
    totalOpportunitiesAnalyzed,
    totalReformulationsGenerated,
    totalEstimatedMonthlyTrafficGain,
    totalEstimatedMonthlyRevenueGain,
    topPriorityReformulations,
    reformulations,
    snippetTypeBreakdown,
    patentRelevance,
    costMetrics,
    windowDate,
  } = snippetCaptureStrategy;

  const remainingReformulations = reformulations.filter(
    (r) => !topPriorityReformulations.some((t) => t.opportunityId === r.opportunityId),
  );

  const maxCount = Math.max(...Object.values(snippetTypeBreakdown).filter((v): v is number => v !== undefined), 1);

  return (
    <section id="audit-snippet-capture" className="space-y-6">
      {/* Header */}
      <div className="flex items-start justify-between gap-4">
        <div>
          <h2 className="text-xl font-bold text-slate-100">Featured Snippet Capture Strategy</h2>
          <p className="text-sm text-slate-400 mt-1">
            Prescriptive reformulation specs for {totalReformulationsGenerated} non-captured snippet opportunities
          </p>
        </div>
        <span className="shrink-0 text-xs text-slate-500">
          {new Date(windowDate).toLocaleDateString("en-US", { month: "short", year: "numeric" })}
        </span>
      </div>

      {/* Revenue impact hero strip */}
      <div className="rounded-2xl bg-gradient-to-br from-slate-800/80 to-slate-900/80 border border-slate-700/50 p-6">
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-6">
          <div className="text-center">
            <p className="text-3xl font-black text-emerald-400">{formatCurrency(totalEstimatedMonthlyRevenueGain)}</p>
            <p className="text-xs text-slate-400 mt-1">Estimated monthly revenue gain</p>
          </div>
          <div className="text-center">
            <p className="text-3xl font-black text-blue-400">{totalEstimatedMonthlyTrafficGain.toLocaleString()}</p>
            <p className="text-xs text-slate-400 mt-1">Estimated monthly sessions</p>
          </div>
          <div className="text-center">
            <p className="text-3xl font-black text-slate-100">{totalReformulationsGenerated}</p>
            <p className="text-xs text-slate-400 mt-1">Reformulations generated from {totalOpportunitiesAnalyzed} opportunities</p>
          </div>
        </div>

        {/* Type breakdown chips */}
        <div className="flex flex-wrap gap-2 mt-5 justify-center">
          {(Object.entries(snippetTypeBreakdown) as [SnippetType, number][]).map(([type, count]) => (
            <span key={type} className="text-xs px-3 py-1 rounded-full bg-slate-700/60 text-slate-300">
              {SNIPPET_TYPE_LABELS[type]}: {count}
            </span>
          ))}
        </div>
      </div>

      {/* Top 5 Priority Reformulations */}
      {topPriorityReformulations.length > 0 && (
        <div className="space-y-3">
          <h3 className="text-sm font-semibold text-slate-300 uppercase tracking-wider">Top Priority Reformulations</h3>
          {topPriorityReformulations.map((r, i) => (
            <ReformulationCard key={r.opportunityId} r={r} index={i} expanded={true} />
          ))}
        </div>
      )}

      {/* Remaining reformulations (collapsed accordion) */}
      {remainingReformulations.length > 0 && (
        <div className="space-y-2">
          <h3 className="text-sm font-semibold text-slate-400 uppercase tracking-wider">
            Additional Reformulations ({remainingReformulations.length})
          </h3>
          {remainingReformulations.map((r, i) => (
            <CompactReformulationRow key={r.opportunityId} r={r} index={i + topPriorityReformulations.length} />
          ))}
        </div>
      )}

      {/* Snippet type breakdown chart */}
      {Object.keys(snippetTypeBreakdown).length > 0 && (
        <div className="rounded-xl bg-slate-900/40 border border-white/10 p-5 space-y-3">
          <h3 className="text-xs font-semibold text-slate-400 uppercase tracking-wider">Snippet Type Breakdown</h3>
          <div className="space-y-2">
            {(Object.entries(snippetTypeBreakdown) as [SnippetType, number][]).sort(([, a], [, b]) => b - a).map(([type, count]) => (
              <div key={type} className="flex items-center gap-3">
                <span className="text-xs text-slate-400 w-28 shrink-0">{SNIPPET_TYPE_LABELS[type]}</span>
                <div className="flex-1 h-2 bg-slate-700/60 rounded-full overflow-hidden">
                  <div
                    className="h-full bg-blue-500 rounded-full"
                    style={{ width: `${Math.round((count / maxCount) * 100)}%` }}
                  />
                </div>
                <span className="text-xs text-slate-300 font-medium w-4 text-right">{count}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Patent relevance */}
      <p className="text-xs text-slate-600 italic">{patentRelevance}</p>

      {costMetrics && (
        <p className="text-xs text-slate-700">
          {costMetrics.reformulationsGenerated} specs generated from {costMetrics.opportunitiesIngested} opportunities in {costMetrics.runtimeSeconds.toFixed(1)}s
          {costMetrics.reformulationsFailed > 0 ? ` (${costMetrics.reformulationsFailed} failed)` : ""}
        </p>
      )}
    </section>
  );
}
