"use client";

import { useState } from "react";
import { ChevronDown, ChevronRight, TrendingUp, AlertTriangle, Info } from "lucide-react";
import type { LostOpportunityCalculation, LostOpportunityEstimate } from "@/lib/audit/types";

interface Props {
  lostOpportunityCalculation: LostOpportunityCalculation | null | undefined;
}

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

function fmtUsd(n: number): string {
  if (n >= 1_000_000) return `$${(n / 1_000_000).toFixed(1)}M`;
  if (n >= 1_000) return `$${Math.round(n / 1000)}k`;
  return `$${n.toLocaleString()}`;
}

function fmtUsdFull(n: number): string {
  return `$${n.toLocaleString()}`;
}

function confidenceBadge(c: "high" | "moderate" | "low") {
  const map = {
    high: "bg-emerald-100 text-emerald-800",
    moderate: "bg-amber-100 text-amber-800",
    low: "bg-slate-100 text-slate-600",
  } as const;
  return map[c];
}

function impactColor(revenue: number, max: number): string {
  const ratio = max > 0 ? revenue / max : 0;
  if (ratio >= 0.7) return "text-emerald-700";
  if (ratio >= 0.4) return "text-amber-700";
  return "text-slate-600";
}

// ─── Top 3 impact cards ───────────────────────────────────────────────────────

function TopImpactCard({
  item,
  index,
  max,
}: {
  item: LostOpportunityCalculation["aggregateOpportunity"]["topThreeMonthlyImpact"][number];
  index: number;
  max: number;
}) {
  const color = impactColor(item.monthlyImpactUsd, max);
  const rankColors = ["border-amber-300 bg-amber-50", "border-slate-300 bg-slate-50", "border-orange-200 bg-orange-50"];
  return (
    <div className={`border rounded-xl p-4 space-y-2 ${rankColors[index] ?? "border-slate-200 bg-white"}`}>
      <div className="flex items-start justify-between gap-2">
        <span className="text-xs font-bold text-slate-400">#{index + 1}</span>
        <span className="text-xs text-slate-500 font-medium">{item.timeToImplement}</span>
      </div>
      <div className={`text-2xl font-extrabold ${color}`}>{fmtUsd(item.monthlyImpactUsd)}<span className="text-sm font-normal text-slate-400">/mo</span></div>
      <div className="text-xs text-slate-700 leading-snug line-clamp-3">{item.findingTitle}</div>
    </div>
  );
}

// ─── Per-finding estimates table ──────────────────────────────────────────────

function FindingsTable({ estimates }: { estimates: LostOpportunityEstimate[] }) {
  const [open, setOpen] = useState(false);
  const [sortKey, setSortKey] = useState<keyof LostOpportunityEstimate>("estimatedRevenueMonthly");
  const [sortAsc, setSortAsc] = useState(false);

  const sorted = [...estimates].sort((a, b) => {
    const av = a[sortKey] as number;
    const bv = b[sortKey] as number;
    return sortAsc ? av - bv : bv - av;
  });

  function toggleSort(key: keyof LostOpportunityEstimate) {
    if (sortKey === key) setSortAsc(!sortAsc);
    else { setSortKey(key); setSortAsc(false); }
  }

  const Th = ({ label, k }: { label: string; k: keyof LostOpportunityEstimate }) => (
    <th
      onClick={() => toggleSort(k)}
      className="px-3 py-2 text-left text-xs font-semibold text-slate-500 uppercase tracking-wide cursor-pointer hover:text-slate-800 select-none whitespace-nowrap"
    >
      {label} {sortKey === k ? (sortAsc ? "↑" : "↓") : ""}
    </th>
  );

  return (
    <div className="border border-slate-200 rounded-xl overflow-hidden">
      <button
        onClick={() => setOpen(!open)}
        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">
          Per-Finding Estimates ({estimates.length} findings)
        </span>
        {open ? <ChevronDown size={14} className="text-slate-400" /> : <ChevronRight size={14} className="text-slate-400" />}
      </button>

      {open && (
        <div className="overflow-x-auto">
          <table className="w-full min-w-[900px] text-xs">
            <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 uppercase tracking-wide">Finding</th>
                <th className="px-3 py-2 text-left text-xs font-semibold text-slate-500 uppercase tracking-wide">Section</th>
                <Th label="Volume/mo" k="affectedQueryVolumeMonthly" />
                <Th label="Recoverable %" k="estimatedRecoverableTrafficPercent" />
                <Th label="Sessions/mo" k="estimatedRecoverableSessionsMonthly" />
                <Th label="Conversions/mo" k="estimatedConversionsMonthly" />
                <Th label="Revenue/mo" k="estimatedRevenueMonthly" />
                <th className="px-3 py-2 text-left text-xs font-semibold text-slate-500 uppercase tracking-wide">Confidence</th>
              </tr>
            </thead>
            <tbody>
              {sorted.map((e, i) => (
                <tr key={i} className={i % 2 === 1 ? "bg-slate-50" : "bg-white"}>
                  <td className="px-3 py-2 text-slate-800 max-w-[220px] truncate" title={e.findingTitle}>{e.findingTitle}</td>
                  <td className="px-3 py-2 text-slate-500">{e.findingSection}</td>
                  <td className="px-3 py-2 text-slate-700 font-mono">{e.affectedQueryVolumeMonthly.toLocaleString()}</td>
                  <td className="px-3 py-2 text-slate-700">{e.estimatedRecoverableTrafficPercent}%</td>
                  <td className="px-3 py-2 text-slate-700 font-mono">{e.estimatedRecoverableSessionsMonthly.toLocaleString()}</td>
                  <td className="px-3 py-2 text-slate-700">{e.estimatedConversionsMonthly.toFixed(1)}</td>
                  <td className="px-3 py-2 font-semibold text-emerald-700">{fmtUsdFull(e.estimatedRevenueMonthly)}</td>
                  <td className="px-3 py-2">
                    <span className={`text-xs px-1.5 py-0.5 rounded-full font-medium ${confidenceBadge(e.confidenceLevel)}`}>
                      {e.confidenceLevel}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

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

export function LostOpportunityCalculatorSection({ lostOpportunityCalculation }: Props) {
  if (!lostOpportunityCalculation?.hasCalculation) return null;

  const loc = lostOpportunityCalculation;
  const agg = loc.aggregateOpportunity;
  const baselines = loc.industryBaselines;
  const maxImpact = agg.topThreeMonthlyImpact[0]?.monthlyImpactUsd ?? 1;

  return (
    <section id="audit-opportunity-estimate" className="space-y-5">
      {/* Header */}
      <div className="flex items-start justify-between gap-3">
        <div>
          <div className="flex items-center gap-2 mb-1">
            <TrendingUp size={18} className="text-emerald-600" />
            <h2 className="text-xl font-bold text-slate-900">Estimated Monthly Opportunity Cost</h2>
          </div>
          <p className="text-sm text-slate-500">
            Directional revenue impact estimates based on industry benchmarks — not measurements
          </p>
        </div>
        <span className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold flex-shrink-0 ${confidenceBadge(loc.confidence)}`}>
          {loc.confidence === "low" && <AlertTriangle size={10} />}
          {loc.confidence.charAt(0).toUpperCase() + loc.confidence.slice(1)} confidence
        </span>
      </div>

      {/* Headline number */}
      <div className="bg-gradient-to-br from-emerald-50 to-teal-50 border border-emerald-200 rounded-2xl p-6 text-center space-y-1">
        <div className="text-5xl font-extrabold text-emerald-700">
          ~{fmtUsd(agg.totalMonthlyOpportunityUsd)}
          <span className="text-2xl font-semibold text-emerald-500"> / month</span>
        </div>
        <div className="text-base text-emerald-600 font-medium">
          ~{fmtUsd(agg.annualizedOpportunityUsd)} annualized
        </div>
        <div className="text-xs text-slate-500 mt-2">
          Estimated based on {baselines.industryVertical} industry conversion rates and customer value baselines
        </div>
      </div>

      {/* Top 3 highest-impact findings */}
      {agg.topThreeMonthlyImpact.length > 0 && (
        <div className="space-y-2">
          <h3 className="text-sm font-semibold text-slate-700">Top findings by revenue impact</h3>
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
            {agg.topThreeMonthlyImpact.map((item, i) => (
              <TopImpactCard key={i} item={item} index={i} max={maxImpact} />
            ))}
          </div>
        </div>
      )}

      {/* Industry baselines used */}
      <div className="bg-slate-50 border border-slate-200 rounded-xl p-4">
        <div className="flex items-center gap-1.5 mb-2">
          <Info size={13} className="text-slate-400" />
          <span className="text-xs font-semibold text-slate-600">Industry baselines used</span>
        </div>
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 text-xs">
          <div>
            <div className="text-slate-400">Industry</div>
            <div className="font-semibold text-slate-800 capitalize">{baselines.industryVertical.replace(/-/g, " ")}</div>
          </div>
          <div>
            <div className="text-slate-400">Avg conversion rate</div>
            <div className="font-semibold text-slate-800">{(baselines.avgConversionRate * 100).toFixed(1)}%</div>
          </div>
          <div>
            <div className="text-slate-400">Avg customer value</div>
            <div className="font-semibold text-slate-800">{fmtUsdFull(baselines.avgCustomerValue)}</div>
          </div>
          <div className="col-span-2 sm:col-span-1">
            <div className="text-slate-400">Source</div>
            <div className="text-slate-600 leading-tight">{baselines.sourceNote}</div>
          </div>
        </div>
      </div>

      {/* Per-finding estimates table */}
      <FindingsTable estimates={loc.perFindingEstimates} />

      {/* Disclosures */}
      <div className="bg-slate-50 border border-slate-200 rounded-xl p-4 space-y-2">
        <div className="flex items-center gap-1.5">
          <AlertTriangle size={12} className="text-amber-500 flex-shrink-0" />
          <span className="text-xs font-semibold text-slate-600">Estimation disclosures</span>
        </div>
        <p className="text-xs text-slate-500 leading-relaxed">{loc.disclosures.estimationDisclosure}</p>
        <p className="text-xs text-slate-500">{loc.disclosures.assumptionsNote}</p>
        {loc.disclosures.confidenceFactors.length > 0 && (
          <ul className="text-xs text-slate-500 space-y-0.5 ml-3 list-disc">
            {loc.disclosures.confidenceFactors.map((f, i) => (
              <li key={i}>{f}</li>
            ))}
          </ul>
        )}
      </div>
    </section>
  );
}
