import Link from "next/link";
import { notFound } from "next/navigation";
import { PORTFOLIO_GOALS } from "@/app/db/schema/portfolio";
import { measuresDisplayLabels, type MeasureKey } from "@/app/db/schema/recommendations";
import { constraintSummary } from "@/lib/scenarios/model";
import { getScenarioWithPlansCount } from "@/lib/scenarios/queries";
import {
  BandChip,
  EPC_SOFT,
  FabricFirstChip,
  GOAL_SHORT_LABELS,
  GoalIcon,
  StatusPill,
  formatDate,
  formatMoney,
  meterGradient,
  meterWidth,
} from "../ui";
import { DetailActions } from "./DetailActions";

export const dynamic = "force-dynamic";

const rowLabel =
  "pt-1 font-manrope text-[11px] font-extrabold uppercase tracking-[.1em] text-gray-400";

export default async function ScenarioDetailPage(props: {
  params: Promise<{ slug: string; scenarioId: string }>;
}) {
  const { slug, scenarioId } = await props.params;
  if (!/^\d+$/.test(scenarioId)) notFound();
  const s = await getScenarioWithPlansCount(BigInt(slug), BigInt(scenarioId));
  if (!s) notFound();

  const isEpc = s.goal === PORTFOLIO_GOALS.EPC && s.goalValue;
  const summary = constraintSummary(s.exclusions);

  return (
    <div className="max-w-8xl mx-auto px-6 pb-16 pt-6">
      <Link
        href={`/portfolio/${slug}/scenarios`}
        className="mb-4 inline-flex items-center gap-1.5 text-[13px] text-gray-600 hover:text-brandblue"
      >
        ← All scenarios
      </Link>
      <div className="max-w-[780px]">
        <DetailActions
          portfolioId={slug}
          scenarioId={String(s.id)}
          name={s.name ?? `Scenario ${s.id}`}
          modelled={s.status === "modelled"}
          plansCount={s.plansCount}
          statusPill={<StatusPill status={s.status} />}
          meta={`Created ${formatDate(s.createdAt)}${
            s.status === "modelled"
              ? ` · modelled against ${s.plansCount.toLocaleString("en-GB")} properties`
              : ""
          } · configuration is fixed — rename any time`}
        >
          <div className="relative overflow-hidden rounded-2xl border border-gray-100 bg-white shadow-sm">
            <span
              aria-hidden
              className="pointer-events-none absolute -right-14 -top-14 h-[170px] w-[170px] rounded-full opacity-[.14] blur-[46px]"
              style={{ background: isEpc ? EPC_SOFT[s.goalValue!] : "#3943b7" }}
            />
            <div className="relative grid grid-cols-[200px_1fr] items-start gap-4 border-b border-gray-100 px-6 py-4">
              <div className={rowLabel}>Goal</div>
              <div className="text-sm">
                <div className="flex items-center gap-2.5 font-semibold text-brandblue">
                  {isEpc ? <BandChip band={s.goalValue!} /> : <GoalIcon />}
                  {isEpc
                    ? `Bring every property to EPC ${s.goalValue}`
                    : GOAL_SHORT_LABELS[s.goal] ?? s.goal}
                  {!isEpc && (
                    <span className="font-normal text-gray-600">
                      — as far as possible{s.budget ? " within budget" : ""}
                    </span>
                  )}
                </div>
                {isEpc && (
                  <div className="mt-3 max-w-[420px]">
                    <div className="h-1.5 overflow-hidden rounded-full bg-gray-100">
                      <i
                        className="block h-full rounded-full"
                        style={{
                          width: meterWidth(s.goalValue!),
                          background: meterGradient(s.goalValue!),
                        }}
                      />
                    </div>
                    <div className="mt-1 flex justify-between font-manrope text-[10px] font-extrabold tracking-wide text-gray-400">
                      {["G", "F", "E", "D", "C", "B", "A"].map((b) => (
                        <span key={b}>{b}</span>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            </div>
            <div className="relative grid grid-cols-[200px_1fr] items-start gap-4 border-b border-gray-100 px-6 py-4">
              <div className={rowLabel}>Housing type</div>
              <div className="text-sm text-brandblue">
                {s.housingType}
                <span className="text-gray-400"> — drives funding treatment</span>
              </div>
            </div>
            <div className="relative grid grid-cols-[200px_1fr] items-start gap-4 border-b border-gray-100 px-6 py-4">
              <div className={rowLabel}>Budget / property</div>
              <div className="text-sm text-brandblue">
                {s.budget ? (
                  formatMoney(s.budget)
                ) : (
                  <span className="text-gray-400">
                    No cap — the engine recommends the maximum interventions
                  </span>
                )}
              </div>
            </div>
            <div className="relative grid grid-cols-[200px_1fr] items-start gap-4 border-b border-gray-100 px-6 py-4">
              <div className={rowLabel}>Exclusions</div>
              <div className="text-sm">
                {summary.kind === "all" ? (
                  <span className="text-gray-400">
                    None — every measure is on the table
                  </span>
                ) : summary.kind === "only" ? (
                  <>
                    <div className="flex flex-wrap gap-1.5">
                      {summary.measures.map((m) => (
                        <span
                          key={m}
                          className="rounded-full border border-gray-200 bg-gray-50 px-3 py-0.5 text-[13px]"
                        >
                          {m}
                        </span>
                      ))}
                    </div>
                    <div className="mt-2 text-xs text-gray-400">
                      Shown as the allowed set — all other measures are excluded.
                    </div>
                  </>
                ) : (
                  <div className="flex flex-wrap gap-1.5">
                    {s.exclusions.map((k) => (
                      <span
                        key={k}
                        className="rounded-full border border-red-100 bg-white px-3 py-0.5 text-[13px] text-red-800 line-through"
                      >
                        {measuresDisplayLabels[k as MeasureKey] ?? k}
                      </span>
                    ))}
                  </div>
                )}
              </div>
            </div>
            <div className="relative grid grid-cols-[200px_1fr] items-start gap-4 px-6 py-4">
              <div className={rowLabel}>Fabric first</div>
              <div className="text-sm text-brandblue">
                {s.fabricFirst ? (
                  <span className="flex flex-wrap items-center gap-2">
                    <FabricFirstChip />
                    <span className="text-gray-600">
                      insulation, glazing &amp; ventilation before heating &amp; renewables
                    </span>
                  </span>
                ) : (
                  <span className="text-gray-400">Off — measures considered together</span>
                )}
              </div>
            </div>
          </div>
        </DetailActions>
      </div>
    </div>
  );
}
