import {
  BoltIcon,
  CloudIcon,
  BanknotesIcon,
  WrenchScrewdriverIcon,
  SparklesIcon,
  BuildingOfficeIcon,
  ShieldCheckIcon,
} from "@heroicons/react/24/outline";
import { CheckCircleIcon, XCircleIcon } from "@heroicons/react/24/solid";
import {
  getPropertyMeta,
  getConditionReport,
  getSpatialData,
  getInstalledMeasuresByUprn,
} from "./utils";
import { HeritageTooltip } from "./HeritageTooltip";
import { CurrentEfficiencyCard } from "@/app/components/building-passport/CurrentEfficiencyCard";

export const revalidate = 1;

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

function formatGbp(value: number | null | undefined): string {
  if (value == null) return "—";
  return `£${Math.round(value).toLocaleString("en-GB")}`;
}

// ── Sub-components ────────────────────────────────────────────────────────────

function SectionHeading({ icon, label }: { icon: React.ReactNode; label: string }) {
  return (
    <div className="flex items-center gap-3 mb-5">
      <span className="text-brandblue">{icon}</span>
      <h2 className="font-manrope font-bold text-sm text-brandblue uppercase tracking-widest">{label}</h2>
    </div>
  );
}

function YesNoBadge({ value }: { value: boolean }) {
  return value ? (
    <span className="inline-flex items-center gap-1 text-xs font-semibold text-emerald-700 bg-emerald-50 border border-emerald-200 px-2 py-0.5 rounded-full">
      <CheckCircleIcon className="w-3 h-3" />
      Yes
    </span>
  ) : (
    <span className="inline-flex items-center gap-1 text-xs font-semibold text-gray-500 bg-gray-50 border border-gray-200 px-2 py-0.5 rounded-full">
      <XCircleIcon className="w-3 h-3" />
      No
    </span>
  );
}

function DetailRow({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <div className="flex items-center justify-between py-3 border-b border-gray-100 last:border-0 gap-4">
      <span className="text-sm text-gray-500 shrink-0">{label}</span>
      <span className="text-sm font-semibold text-brandblue text-right">{value}</span>
    </div>
  );
}

// ── Page ──────────────────────────────────────────────────────────────────────

export default async function BuildingPassportHome(props: {
  params: Promise<{ slug: string; propertyId: string }>;
}) {
  const params = await props.params;
  const propertyMeta = await getPropertyMeta(params.propertyId);
  const conditionReport = await getConditionReport(params.propertyId);
  const spatial = await getSpatialData(propertyMeta.uprn);
  const installedMeasures = await getInstalledMeasuresByUprn(Number(propertyMeta.uprn));

  const annualEnergyCost =
    (conditionReport.heatingEnergyCostCurrent ?? 0) +
    (conditionReport.hotWaterEnergyCostCurrent ?? 0) +
    (conditionReport.lightingEnergyCostCurrent ?? 0);

  return (
    <div className="max-w-7xl mx-auto px-6 py-10 space-y-6">

      {/* ── Row 1: EPC Hero + Energy Stats ──────────────────────────────── */}
      <div className="grid grid-cols-12 gap-6">

        {/* EPC Hero */}
        <CurrentEfficiencyCard
          epcRating={propertyMeta.currentEpcRating ?? null}
          sapPoints={propertyMeta.currentSapPoints ?? 0}
          originalSapPoints={propertyMeta.originalSapPoints}
        />

        {/* Energy Stats + Heritage Status */}
        <div className="col-span-12 lg:col-span-7 flex flex-col gap-4">

          {/* 3 stat cards */}
          <div className="grid grid-cols-3 gap-4">

            {/* Stat: Energy Demand */}
            <div className="bg-gray-50 rounded-2xl p-7 flex flex-col justify-between">
              <BoltIcon className="w-6 h-6 text-brandmidblue mb-4" />
              <div>
                <p className="text-xs font-bold text-gray-400 uppercase tracking-wider mb-1">Energy Demand</p>
                <p className="font-manrope text-2xl font-black text-brandblue">
                  {conditionReport.currentEnergyDemand != null
                    ? Math.round(conditionReport.currentEnergyDemand).toLocaleString("en-GB")
                    : "—"}
                  <span className="text-sm font-bold text-gray-400 ml-1.5">kWh/yr</span>
                </p>
              </div>
            </div>

            {/* Stat: CO₂ Emissions */}
            <div className="bg-gray-50 rounded-2xl p-7 flex flex-col justify-between">
              <CloudIcon className="w-6 h-6 text-brandmidblue mb-4" />
              <div>
                <p className="text-xs font-bold text-gray-400 uppercase tracking-wider mb-1">CO₂ Emissions</p>
                <p className="font-manrope text-2xl font-black text-brandblue">
                  {conditionReport.co2Emissions != null
                    ? conditionReport.co2Emissions.toFixed(1)
                    : "—"}
                  <span className="text-sm font-bold text-gray-400 ml-1.5">t CO₂/yr</span>
                </p>
              </div>
            </div>

            {/* Stat: Annual Bills */}
            <div className="bg-gray-50 rounded-2xl p-7 flex flex-col justify-between">
              <BanknotesIcon className="w-6 h-6 text-brandmidblue mb-4" />
              <div>
                <p className="text-xs font-bold text-gray-400 uppercase tracking-wider mb-1">Est. Annual Bills</p>
                <p className="font-manrope text-2xl font-black text-brandblue">
                  {annualEnergyCost > 0 ? `£${Math.round(annualEnergyCost).toLocaleString("en-GB")}` : "—"}
                </p>
              </div>
            </div>
          </div>

          {/* Heritage Status — fills remaining height to match EPC card */}
          <div className="flex-1 bg-white rounded-2xl p-8 shadow-sm border border-gray-100 flex flex-col justify-between">
            <div>
              <div className="flex items-center gap-3 mb-6">
                <span className="w-8 h-8 rounded-xl bg-brandblue/8 flex items-center justify-center shrink-0">
                  <ShieldCheckIcon className="w-4 h-4 text-brandblue" />
                </span>
                <p className="font-manrope text-xs font-bold text-brandmidblue uppercase tracking-widest">Heritage & Planning Status</p>
                <HeritageTooltip />
              </div>
              <div className="grid grid-cols-3 gap-4">
                <div className="flex flex-col gap-3">
                  <p className="text-xs font-bold text-gray-400 uppercase tracking-wider">Conservation Area</p>
                  <YesNoBadge value={!!spatial.conservationStatus} />
                  <p className="text-xs text-gray-400 leading-relaxed">
                    {spatial.conservationStatus
                      ? "This property falls within a designated conservation area."
                      : "No conservation area restrictions apply to this property."}
                  </p>
                </div>
                <div className="flex flex-col gap-3">
                  <p className="text-xs font-bold text-gray-400 uppercase tracking-wider">Listed Building</p>
                  <YesNoBadge value={!!spatial.isListedBuilding} />
                  <p className="text-xs text-gray-400 leading-relaxed">
                    {spatial.isListedBuilding
                      ? "This property is a listed building with statutory protections."
                      : "This property does not have listed building status."}
                  </p>
                </div>
                <div className="flex flex-col gap-3">
                  <p className="text-xs font-bold text-gray-400 uppercase tracking-wider">Heritage Building</p>
                  <YesNoBadge value={!!spatial.isHeritageBuilding} />
                  <p className="text-xs text-gray-400 leading-relaxed">
                    {spatial.isHeritageBuilding
                      ? "This property is recognised as a heritage asset."
                      : "No heritage asset designation applies to this property."}
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* ── Row 2: Property Details Grid ────────────────────────────────── */}
      <div>
        <SectionHeading
          icon={<BuildingOfficeIcon className="w-4 h-4" />}
          label="Property Details"
        />
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">

          {/* Building */}
          <div className="bg-white rounded-2xl p-7 shadow-sm border border-gray-100">
            <p className="font-manrope text-xs font-bold text-brandmidblue uppercase tracking-widest mb-4">Building</p>
            <DetailRow label="Year built" value={propertyMeta.yearBuilt ?? "—"} />
            <DetailRow
              label="Type"
              value={[propertyMeta.builtForm, propertyMeta.propertyType].filter(Boolean).join(", ") || "—"}
            />
            <DetailRow
              label="Floor area"
              value={
                conditionReport.totalFloorArea != null
                  ? <>{Math.round(conditionReport.totalFloorArea)} m²</>
                  : "—"
              }
            />
            <DetailRow label="Storeys" value={conditionReport.numberStoreys ?? "—"} />
            <DetailRow label="Habitable rooms" value={propertyMeta.numberOfRooms ?? "—"} />
            <DetailRow
              label="Mains gas"
              value={
                conditionReport.mainsGas != null
                  ? <YesNoBadge value={conditionReport.mainsGas} />
                  : "—"
              }
            />
          </div>

          {/* Location & Status */}
          <div className="bg-white rounded-2xl p-7 shadow-sm border border-gray-100">
            <p className="font-manrope text-xs font-bold text-brandmidblue uppercase tracking-widest mb-4">Location & Status</p>
            <DetailRow label="Local authority" value={propertyMeta.localAuthority ?? "—"} />
            <DetailRow label="Constituency" value={propertyMeta.constituency ?? "—"} />
            <DetailRow label="Tenure" value={propertyMeta.tenure ?? "—"} />
          </div>

          {/* Annual Energy Costs */}
          <div className="bg-white rounded-2xl p-7 shadow-sm border border-gray-100">
            <p className="font-manrope text-xs font-bold text-brandmidblue uppercase tracking-widest mb-4">Annual Energy Costs</p>
            <DetailRow label="Heating" value={formatGbp(conditionReport.heatingEnergyCostCurrent)} />
            <DetailRow label="Hot water" value={formatGbp(conditionReport.hotWaterEnergyCostCurrent)} />
            <DetailRow label="Lighting" value={formatGbp(conditionReport.lightingEnergyCostCurrent)} />
            <DetailRow label="Appliances" value={formatGbp(conditionReport.appliancesEnergyCostCurrent)} />
            {annualEnergyCost > 0 && (
              <div className="mt-3 pt-3 border-t border-gray-200 flex justify-between">
                <span className="text-sm font-bold text-gray-600">Total (excl. appliances)</span>
                <span className="text-sm font-bold text-brandblue tabular-nums">
                  £{Math.round(annualEnergyCost).toLocaleString("en-GB")}
                </span>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* ── Row 3: Installed Measures ────────────────────────────────────── */}
      {installedMeasures.length > 0 && (
        <div>
          <SectionHeading
            icon={<WrenchScrewdriverIcon className="w-4 h-4" />}
            label="Installed Measures"
          />
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            {installedMeasures.map((measure, i) => (
              <div
                key={i}
                className="bg-white rounded-2xl border border-gray-100 p-6 shadow-sm flex flex-col gap-3"
              >
                <div className="flex items-center gap-3">
                  <span className="w-8 h-8 rounded-xl bg-brandblue/8 flex items-center justify-center shrink-0">
                    <SparklesIcon className="w-4 h-4 text-brandblue" />
                  </span>
                  <span className="text-sm font-bold text-brandblue">{measure.measureType}</span>
                </div>
                {measure.installedAt && (
                  <p className="text-xs text-gray-400">
                    Installed {new Date(measure.installedAt).toLocaleDateString("en-GB", { month: "short", year: "numeric" })}
                  </p>
                )}
                <div className="grid grid-cols-2 gap-2 mt-1">
                  {measure.kwhSavings != null && (
                    <div>
                      <p className="text-[10px] uppercase tracking-wide text-gray-400 font-medium">kWh saved</p>
                      <p className="text-sm font-semibold text-brandblue tabular-nums">
                        {Math.round(measure.kwhSavings).toLocaleString()}/yr
                      </p>
                    </div>
                  )}
                  {measure.billSavings != null && (
                    <div>
                      <p className="text-[10px] uppercase tracking-wide text-gray-400 font-medium">Bill saving</p>
                      <p className="text-sm font-semibold text-brandblue tabular-nums">
                        £{Math.round(measure.billSavings).toLocaleString()}/yr
                      </p>
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

    </div>
  );
}
