import RecommendationContainer from "@/app/components/building-passport/RecommendationContainer";
import {
  getPropertyMeta,
  getRecommendations,
  getPlanMeta,
  getInstalledMeasuresByUprn,
  getScenario,
} from "../../utils";
import { sapToEpc, formatNumber } from "@/app/utils";
import {
  CloudIcon,
  BoltIcon,
  CurrencyPoundIcon,
  BuildingOfficeIcon,
  InformationCircleIcon,
} from "@heroicons/react/24/outline";

function getEpcHex(letter: string | null | undefined): string {
  switch (letter?.toUpperCase()) {
    case "A":
      return "#117d58";
    case "B":
      return "#2da55c";
    case "C":
      return "#8dbd40";
    case "D":
      return "#f7cd14";
    case "E":
      return "#f3a96a";
    case "F":
      return "#ef8026";
    case "G":
      return "#e41e3b";
    default:
      return "#9ca3af";
  }
}

// G on left (worst), A on right (best) — correct EPC scale direction
const EPC_LETTERS = ["G", "F", "E", "D", "C", "B", "A"];

// Returns the horizontal centre position (%) of each EPC band in the 7-segment bar
function epcToBandCenter(letter: string | null | undefined): number {
  if (!letter) return 0;
  const map: Record<string, number> = {
    G: 0,
    F: 1,
    E: 2,
    D: 3,
    C: 4,
    B: 5,
    A: 6,
  };
  const idx = map[letter.toUpperCase()] ?? 0;
  return ((idx + 0.5) / 7) * 100;
}

export default async function PlanDetail(props: {
  params: Promise<{ slug: string; propertyId: string; planId: string }>;
}) {
  const params = await props.params;
  const propertyMeta = await getPropertyMeta(params.propertyId);
  const [recommendations, planMeta, installedMeasures, scenarioData] =
    await Promise.all([
      getRecommendations(params.planId),
      getPlanMeta(params.planId),
      getInstalledMeasuresByUprn(propertyMeta.uprn),
      getScenario(params.planId),
    ]);

  const currentEpc = propertyMeta.currentEpcRating;
  const targetEpc =
    planMeta.postEpcRating ??
    (planMeta.postSapPoints ? sapToEpc(planMeta.postSapPoints) : null);

  const valuationLabel = (() => {
    if (planMeta.valuationIncreaseAverage)
      return `+${planMeta.valuationIncreaseAverage.toFixed(1)}%`;
    if (
      planMeta.valuationIncreaseLowerBound &&
      planMeta.valuationIncreaseUpperBound
    )
      return `+${planMeta.valuationIncreaseLowerBound.toFixed(0)}–${planMeta.valuationIncreaseUpperBound.toFixed(0)}%`;
    if (planMeta.valuationIncrease)
      return `+${planMeta.valuationIncrease.toFixed(1)}%`;
    return null;
  })();

  return (
    <div className="max-w-[1400px] mx-auto py-6 space-y-12">
      {/* ── Header ─────────────────────────────────────────────────── */}
      <div>
        <h2 className="text-brandblue text-2xl md:text-5xl font-black font-manrope tracking-tighter text-brandblue mb-2">
          Plan: {planMeta.name ?? "Retrofit Plan"}
        </h2>
      </div>

      {/* ── Executive Summary Bento ──────────────────────────────────── */}
      <section className="grid grid-cols-1 md:grid-cols-4 lg:grid-cols-6 gap-6">
        {/* EPC Rating card */}
        <div className="md:col-span-2 lg:col-span-2 bg-white p-7 rounded-2xl border border-gray-100 shadow-sm flex flex-col justify-between relative overflow-hidden group">
          {/* Decorative corner accent */}
          <div className="absolute top-0 right-0 w-32 h-32 bg-green-500/5 rounded-bl-full -mr-10 -mt-10 transition-transform duration-700 group-hover:scale-110" />

          <div>
            {/* Header label with decorative line */}
            <div className="flex items-center gap-2 mb-7">
              <span className="text-[10px] font-bold uppercase tracking-[0.2em] text-brandbrown whitespace-nowrap">
                EPC UPGRADE
              </span>
              <div className="h-px flex-1 bg-brandbrown/20" />
            </div>

            {/* Current → Target letter badges */}
            <div className="flex items-center justify-between mb-8">
              <div className="flex flex-col">
                <span className="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-1">
                  Current
                </span>
                <span
                  className="text-5xl font-black font-manrope leading-none"
                  style={{ color: getEpcHex(currentEpc) }}
                >
                  {currentEpc ?? "–"}
                </span>
              </div>
              <svg
                className="w-8 h-8 text-gray-300 shrink-0 animate-pulse"
                fill="none"
                stroke="currentColor"
                strokeWidth={1.5}
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M17 8l4 4m0 0l-4 4m4-4H3"
                />
              </svg>
              <div className="flex flex-col items-end">
                <span className="text-[10px] font-bold text-green-500 uppercase tracking-wider mb-1">
                  Target
                </span>
                <div className="relative">
                  <span
                    className="text-7xl font-black font-manrope leading-none"
                    style={{
                      color: getEpcHex(targetEpc),
                      filter: "drop-shadow(0 10px 15px rgba(34,197,94,0.3))",
                    }}
                  >
                    {targetEpc ?? "–"}
                  </span>
                </div>
              </div>
            </div>
          </div>

          <div>
            {/* Gradient bar with current-position marker */}
            <div className="relative h-2 w-full bg-gray-100 rounded-full overflow-hidden mb-5">
              <div
                className="absolute inset-0 opacity-90"
                style={{
                  background:
                    "linear-gradient(90deg, #ba1a1a 0%, #c4a47c 50%, #22c55e 100%)",
                }}
              />
              {currentEpc && (
                <div
                  className="absolute top-0 h-full w-1 bg-white shadow-sm z-10"
                  style={{ left: `${epcToBandCenter(currentEpc)}%` }}
                />
              )}
            </div>

            {/* Bottom: SAP points summary */}
            <div className="flex justify-between items-end">
              <div className="space-y-0.5">
                <p className="text-xs font-bold font-manrope text-brandblue tracking-tight">
                  Projected Rating Increase
                </p>
                <p className="text-[11px] text-gray-500 font-medium">
                  Improvement from{" "}
                  <span
                    className="font-bold"
                    style={{ color: getEpcHex(currentEpc) }}
                  >
                    {propertyMeta.currentSapPoints != null
                      ? Math.round(propertyMeta.currentSapPoints)
                      : "–"}
                  </span>{" "}
                  to{" "}
                  <span className="font-bold text-green-500">
                    {planMeta.postSapPoints?.toFixed(1) ?? "–"}
                  </span>{" "}
                  SAP points
                </p>
              </div>
              <svg
                className="w-5 h-5 text-brandbrown shrink-0"
                fill="none"
                stroke="currentColor"
                strokeWidth={2}
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                />
              </svg>
            </div>
          </div>
        </div>

        {/* 4 stat tiles — cool blue background, icon at top */}
        <div className="md:col-span-2 lg:col-span-4 grid grid-cols-2 gap-4">
          <div className="bg-blue-50 p-5 rounded-xl flex flex-col justify-between gap-3 border border-blue-100">
            <CloudIcon className="w-8 h-8 text-brandmidblue" />
            <p className="text-2xl font-bold font-manrope text-brandblue">
              {planMeta.co2Savings != null
                ? `${planMeta.co2Savings.toFixed(1)}t`
                : "—"}
            </p>
            <p className="text-[10px] text-gray-500 font-bold uppercase tracking-widest leading-tight">
              CO₂ Reduction /yr
            </p>
          </div>

          <div className="bg-blue-50 p-5 rounded-xl flex flex-col justify-between gap-3 border border-blue-100">
            <BoltIcon className="w-8 h-8 text-brandmidblue" />
            <p className="text-2xl font-bold font-manrope text-brandblue">
              {planMeta.energyConsumptionSavings != null
                ? `${formatNumber(planMeta.energyConsumptionSavings)} kWh`
                : "—"}
            </p>
            <p className="text-[10px] text-gray-500 font-bold uppercase tracking-widest leading-tight">
              Energy Savings /yr
            </p>
          </div>

          <div className="bg-blue-50 p-5 rounded-xl flex flex-col justify-between gap-3 border border-blue-100">
            <CurrencyPoundIcon className="w-8 h-8 text-brandmidblue" />
            <p className="text-2xl font-bold font-manrope text-brandblue">
              {planMeta.energyBillSavings != null
                ? `£${formatNumber(planMeta.energyBillSavings)}`
                : "—"}
            </p>
            <p className="text-[10px] text-gray-500 font-bold uppercase tracking-widest leading-tight">
              Bill Reduction /yr
            </p>
          </div>

          <div className="bg-blue-50 p-5 rounded-xl flex flex-col justify-between gap-3 border border-blue-100">
            <BuildingOfficeIcon className="w-8 h-8 text-brandmidblue" />
            <p className="text-2xl font-bold font-manrope text-brandblue">
              {valuationLabel ?? "—"}
            </p>
            <p className="text-[10px] text-gray-500 font-bold uppercase tracking-widest leading-tight">
              Valuation Boost
            </p>
          </div>
        </div>
      </section>

      {/* ── Financial + Recommendations ──────────────────────────────── */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-12 items-start">
        {/* Left: Financial Overview — sticky so it stays visible while scrolling recs */}
        <div className="lg:col-span-4 space-y-6 lg:sticky lg:top-8">
          <h3 className="text-xs font-bold uppercase tracking-widest text-gray-500">
            Financial Overview
          </h3>

          <div className="bg-brandblue text-white p-8 rounded-2xl shadow-xl shadow-brandblue/10">
            <div className="mb-8">
              <p className="text-white/60 text-sm font-medium mb-1 uppercase tracking-wider">
                Total Investment
              </p>
              <p className="text-5xl font-black font-manrope">
                {planMeta.costOfWorks != null
                  ? `£${formatNumber(planMeta.costOfWorks)}`
                  : "—"}
              </p>
            </div>
            <div className="pt-6 border-t border-white/10 flex justify-between items-center">
              <div>
                <p className="text-white/60 text-[10px] font-bold uppercase tracking-widest">
                  Contingency
                </p>
                <p className="text-xl font-bold font-manrope text-brandbrown">
                  {planMeta.contingencyCost != null &&
                  planMeta.contingencyCost > 0
                    ? `£${formatNumber(planMeta.contingencyCost)}`
                    : "—"}
                </p>
              </div>
              {/* Contingency tooltip */}
              <div className="relative group cursor-help">
                <InformationCircleIcon className="w-5 h-5 text-white/40 group-hover:text-white/80 transition-colors" />
                <div className="absolute bottom-full right-0 mb-3 w-64 bg-gray-900 text-white text-xs rounded-xl p-3.5 shadow-2xl z-20 opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none">
                  <p className="leading-relaxed text-white/90">
                    A contingency buffer is added on top of estimated costs to
                    account for unexpected variations in materials or labour.
                    Rates vary per measure type.
                  </p>
                  <div className="absolute top-full right-4 border-4 border-transparent border-t-gray-900" />
                </div>
              </div>
            </div>
          </div>

          <p className="text-sm text-gray-600 leading-relaxed">
            Based on current market rates and property size. Final quotes may
            vary following a technical survey. Contingency rates vary per
            measure type.
          </p>

          {/* About These Estimates box */}
          <div className="bg-brandlightblue rounded-xl border border-blue-100 p-5">
            <div className="flex items-start gap-3">
              <InformationCircleIcon className="w-4 h-4 text-brandblue mt-0.5 shrink-0" />
              <div>
                <p className="text-xs font-bold text-brandblue uppercase tracking-widest mb-2">
                  About These Estimates
                </p>
                <ul className="space-y-1.5">
                  <li className="text-xs text-gray-600 leading-relaxed flex items-start gap-1.5">
                    <span className="text-brandblue mt-0.5 shrink-0">·</span>
                    Costs modelled using current market rates and SAP 10.2
                    methodology.
                  </li>
                  <li className="text-xs text-gray-600 leading-relaxed flex items-start gap-1.5">
                    <span className="text-brandblue mt-0.5 shrink-0">·</span>
                    Annual savings are projected based on typical occupancy
                    patterns.
                  </li>
                  <li className="text-xs text-gray-600 leading-relaxed flex items-start gap-1.5">
                    <span className="text-brandblue mt-0.5 shrink-0">·</span>
                    Final quotes confirmed after a technical survey of the
                    property.
                  </li>
                </ul>
              </div>
            </div>
          </div>

          {/* Scenario Configuration */}
          {scenarioData && (
            <div className="bg-white rounded-xl border border-gray-100 p-5 space-y-3">
              <p className="text-xs font-bold text-brandblue uppercase tracking-widest">
                Scenario Configuration
              </p>
              {scenarioData.name && (
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">Scenario</span>
                  <span className="font-semibold text-gray-800">
                    {scenarioData.name}
                  </span>
                </div>
              )}
              <div className="flex justify-between text-sm">
                <span className="text-gray-500">Housing type</span>
                <span className="font-semibold text-gray-800">
                  {scenarioData.housingType}
                </span>
              </div>
              {scenarioData.budget != null && (
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">Budget</span>
                  <span className="font-semibold text-gray-800">
                    £{formatNumber(scenarioData.budget)}
                  </span>
                </div>
              )}
              {scenarioData.goal && (
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">Goal</span>
                  <span className="font-semibold text-gray-800 text-right">
                    {scenarioData.goal}
                    {scenarioData.goalValue
                      ? ` → ${scenarioData.goalValue}`
                      : ""}
                  </span>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Right: Recommended Upgrades — scrollable to avoid excessive page length */}
        <div className="lg:col-span-8">
          <h3 className="text-xs font-bold uppercase tracking-widest text-gray-500 mb-8 flex items-center gap-3">
            Recommended Upgrades
            <div className="h-px flex-grow bg-gray-100" />
          </h3>

          <div className="overflow-y-auto max-h-[780px] pr-2 -mr-2 pb-24">
            <RecommendationContainer
              recommendations={recommendations}
              installedMeasures={installedMeasures}
              planId={params.planId}
              slug={params.slug}
              propertyId={params.propertyId}
              currentSapPoints={propertyMeta.currentSapPoints ?? 0}
              savedCostOfWorks={planMeta.costOfWorks ?? 0}
              savedContingencyCost={planMeta.contingencyCost ?? 0}
            />
          </div>
        </div>
      </div>
    </div>
  );
}
