import { PORTFOLIO_GOALS } from "@/app/db/schema/portfolio";
import type { ScenarioStatus } from "@/lib/scenarios/model";
import { constraintSummary } from "@/lib/scenarios/model";

/** Softened EPC palette from the building-passport efficiency meter. */
export const EPC_SOFT: Record<string, string> = {
  A: "#117d58",
  B: "#2da55c",
  C: "#8dbd40",
  D: "#f7cd14",
  E: "#f3a96a",
  F: "#ee8749",
  G: "#e25c50",
};
const DARK_TEXT_BANDS = new Set(["C", "D", "E"]);

/** Letter ink with adequate contrast on the band's full colour (dark on the light mid-bands, white on the saturated ends). */
export function bandInk(band: string): string {
  return DARK_TEXT_BANDS.has(band) ? "#333a1d" : "#fff";
}

/** The band colour as a light tint — used for unselected picker chips so every letter can share one dark ink. */
export function bandTint(band: string, alpha = 0.22): string {
  const hex = (EPC_SOFT[band] ?? "#9ca3af").slice(1);
  const [r, g, b] = [0, 2, 4].map((i) => parseInt(hex.slice(i, i + 2), 16));
  return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}

export const GOAL_DESCRIPTIONS: Record<string, string> = {
  [PORTFOLIO_GOALS.EPC]: "Bring every property up to a target band.",
  [PORTFOLIO_GOALS.CO2]: "Cut carbon as far as possible, within any budget you set.",
  [PORTFOLIO_GOALS.ENERGY]: "Cut kWh demand as far as possible, within any budget you set.",
  [PORTFOLIO_GOALS.VALUATION]: "Maximise property value uplift, within any budget you set.",
};
export const GOAL_SHORT_LABELS: Record<string, string> = {
  [PORTFOLIO_GOALS.EPC]: "Increase EPC rating",
  [PORTFOLIO_GOALS.CO2]: "Reduce CO₂ emissions",
  [PORTFOLIO_GOALS.ENERGY]: "Save energy",
  [PORTFOLIO_GOALS.VALUATION]: "Improve valuation",
};

/** G→band gradient, mirroring the passport's getEpcGradient. */
export function meterGradient(band: string): string {
  const order = ["G", "F", "E", "D", "C", "B", "A"];
  const upto = order.slice(0, order.indexOf(band) + 1);
  const stops = upto.map(
    (b, i) => `${EPC_SOFT[b]} ${((i / Math.max(upto.length - 1, 1)) * 100).toFixed(0)}%`,
  );
  return `linear-gradient(to right, ${stops.join(", ")})`;
}
export function meterWidth(band: string): string {
  return { G: "16%", F: "30%", E: "44%", D: "58%", C: "72%", B: "86%", A: "100%" }[band] ?? "0%";
}

export function BandChip({ band, size = 34 }: { band: string; size?: number }) {
  return (
    <span
      className="inline-flex flex-none items-center justify-center rounded-lg font-manrope font-extrabold"
      style={{
        width: size,
        height: size,
        fontSize: size / 2,
        background: EPC_SOFT[band],
        color: bandInk(band),
        boxShadow: "inset 0 -10px 14px rgba(0,0,0,.12)",
      }}
    >
      {band}
    </span>
  );
}

export function GoalIcon({ size = 34 }: { size?: number }) {
  return (
    <span
      className="inline-flex flex-none items-center justify-center rounded-lg text-white font-bold"
      style={{
        width: size,
        height: size,
        background: "linear-gradient(135deg,#14163d,#3943b7)",
      }}
    >
      ↓
    </span>
  );
}

export function StatusPill({
  status,
  className = "",
}: {
  status: ScenarioStatus;
  className?: string;
}) {
  const modelled = status === "modelled";
  return (
    <span
      className={`inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-xs font-semibold ${
        modelled ? "bg-brandlightblue text-brandmidblue" : "bg-amber-50 text-amber-800"
      } ${className}`}
    >
      <span
        className={`h-1.5 w-1.5 flex-none rounded-full ${modelled ? "bg-brandmidblue" : "bg-brandgold"}`}
      />
      {modelled ? "Modelled" : "Awaiting modelling"}
    </span>
  );
}

export function constraintLine(exclusions: string[]): React.ReactNode {
  const summary = constraintSummary(exclusions);
  if (summary.kind === "all")
    return (
      <>
        <b className="font-semibold text-brandblue">All measures</b> on the table
      </>
    );
  if (summary.kind === "only")
    return (
      <>
        Only: <b className="font-semibold text-brandblue">{summary.measures.join(", ")}</b>
      </>
    );
  return (
    <>
      Excludes{" "}
      <b className="font-semibold text-brandblue">
        {summary.measures.length} measure{summary.measures.length > 1 ? "s" : ""}
      </b>
    </>
  );
}

/** Small badge marking a fabric-first Scenario. Render only when the flag is set. */
export function FabricFirstChip({ className = "" }: { className?: string }) {
  return (
    <span
      className={`inline-flex items-center gap-1 rounded-full bg-emerald-50 px-2 py-0.5 text-[11px] font-semibold text-emerald-800 ${className}`}
      title="Insulation, glazing and ventilation are applied before heating and renewables."
    >
      <span aria-hidden className="h-1.5 w-1.5 flex-none rounded-full bg-emerald-500" />
      Fabric first
    </span>
  );
}

export const formatDate = (d: Date | string) =>
  new Date(d).toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" });

export const formatMoney = (n: number) => "£" + n.toLocaleString("en-GB");
