import { sapToEpc } from "@/app/utils";
import { EpcInfoTooltip } from "./EpcInfoTooltip";
import { LodgedEpcTooltip } from "./LodgedEpcTooltip";

interface CurrentEfficiencyCardProps {
  epcRating: string | null;
  sapPoints: number;
  provenanceSignal?: "estimated" | "remodelled" | "none";
  lodgedEpcRating?: string | null;
  lodgedSapPoints?: number | null;
  originalSapPoints?: number | null;
}

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";
  }
}

const EPC_STOPS = [
  { sap: 0,  color: "#e41e3b" }, // G
  { sap: 21, color: "#ef8026" }, // F
  { sap: 39, color: "#f3a96a" }, // E
  { sap: 55, color: "#f7cd14" }, // D
  { sap: 69, color: "#8dbd40" }, // C
  { sap: 81, color: "#2da55c" }, // B
  { sap: 92, color: "#117d58" }, // A
];

function getEpcGradient(sapPoints: number, epcHex: string): string {
  if (sapPoints <= 0) return epcHex;
  const stops = EPC_STOPS.filter(s => s.sap <= sapPoints);
  const gradientStops = stops.map(s => {
    const pct = s.sap === 0 ? 0 : (s.sap / sapPoints) * 100;
    return `${s.color} ${pct.toFixed(1)}%`;
  });
  gradientStops.push(`${epcHex} 100%`);
  return `linear-gradient(to right, ${gradientStops.join(", ")})`;
}

function getEpcDescription(letter: string | null | undefined): string {
  switch (letter?.toUpperCase()) {
    case "A":
    case "B": return "This property is performing at or above modern energy standards.";
    case "C": return "This property meets modern energy performance benchmarks.";
    case "D": return "This property is performing slightly below modern energy standards.";
    case "E": return "This property is performing below modern energy standards.";
    case "F":
    case "G": return "This property is performing significantly below modern energy standards.";
    default:  return "Energy performance data is not yet available for this property.";
  }
}

export function CurrentEfficiencyCard({
  epcRating,
  sapPoints,
  provenanceSignal = "none",
  lodgedEpcRating,
  lodgedSapPoints,
  originalSapPoints,
}: CurrentEfficiencyCardProps) {
  const epcHex = getEpcHex(epcRating);
  // New-approach: show the lodged certificate whenever the property was
  // re-modelled (effective diverged from lodged), even within the same band.
  // Legacy: fall back to the row's originalSapPoints, only when the band differs.
  const legacyLodgedLetter = originalSapPoints ? sapToEpc(originalSapPoints) : null;
  const remodelled = provenanceSignal === "remodelled";
  const lodgedLetter = remodelled
    ? lodgedEpcRating ?? null
    : legacyLodgedLetter !== epcRating
      ? legacyLodgedLetter
      : null;
  const lodgedBadgeSap = remodelled ? lodgedSapPoints : originalSapPoints;
  const showLodgedBadge = lodgedLetter !== null;
  const lodgedHex = getEpcHex(lodgedLetter);

  return (
    <section className="col-span-12 lg:col-span-5 bg-white rounded-2xl p-10 flex flex-col justify-between shadow-sm border border-gray-100 relative overflow-hidden">
      <div
        className="absolute top-0 right-0 w-72 h-72 rounded-full blur-3xl -mr-20 -mt-20 opacity-10"
        style={{ backgroundColor: epcHex }}
      />

      {showLodgedBadge && (
        <div className="absolute top-3 right-3 z-20 rounded-xl border-2 border-brandbrown/60 bg-white/90 px-3 py-2.5 shadow-sm">
          <div className="flex items-center gap-1 mb-1">
            <span className="text-[9px] font-bold uppercase tracking-widest text-brandbrown">
              Lodged EPC
            </span>
            <LodgedEpcTooltip />
          </div>
          <div className="flex items-baseline gap-1.5">
            <span
              className="text-2xl font-black font-manrope leading-none"
              style={{ color: lodgedHex }}
            >
              {lodgedLetter}
            </span>
            {lodgedBadgeSap != null && (
              <span className="text-xs font-bold text-gray-400">
                / {Math.round(lodgedBadgeSap)}
              </span>
            )}
          </div>
        </div>
      )}

      <div className="relative z-10">
        <div className="flex items-center gap-2 mb-6">
          <p className="font-manrope text-xs font-bold text-brandmidblue uppercase tracking-widest">
            Current Efficiency State
          </p>
          <EpcInfoTooltip />
        </div>
        <div className="flex items-baseline gap-4 mb-4">
          <span
            className="text-[110px] font-black font-manrope leading-none tracking-tighter"
            style={{ color: epcHex }}
          >
            {epcRating ?? "—"}
          </span>
          <span className="text-4xl font-bold font-manrope text-gray-400">
            / {sapPoints || "—"}
          </span>
        </div>
        <p className="text-gray-500 font-medium text-sm max-w-xs leading-relaxed">
          {getEpcDescription(epcRating)}
        </p>
      </div>

      <div className="mt-10 space-y-3">
        <div className="relative h-2.5 w-full bg-gray-100 rounded-full overflow-hidden">
          <div
            className="absolute inset-y-0 left-0 rounded-full"
            style={{
              width: `${Math.min(100, Math.max(2, sapPoints))}%`,
              background: getEpcGradient(sapPoints, epcHex),
            }}
          />
        </div>
        <div className="flex justify-between text-[10px] font-bold text-gray-400 uppercase tracking-wider">
          <span>Very Inefficient</span>
          <span>Very Efficient</span>
        </div>
      </div>
    </section>
  );
}
