import Link from "next/link";
import { PORTFOLIO_GOALS } from "@/app/db/schema/portfolio";
import { listScenariosWithStatus } from "@/lib/scenarios/queries";
import {
  BandChip,
  EPC_SOFT,
  FabricFirstChip,
  GOAL_SHORT_LABELS,
  GoalIcon,
  StatusPill,
  constraintLine,
  formatDate,
  formatMoney,
  meterGradient,
  meterWidth,
} from "./ui";

export const dynamic = "force-dynamic";

export default async function ScenariosPage(props: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await props.params;
  const scenarios = await listScenariosWithStatus(BigInt(slug));

  return (
    <div className="max-w-8xl mx-auto px-6 pb-16 pt-6">
      <div className="mb-2 flex items-end justify-between gap-4">
        <div className="min-w-0">
          <span className="font-manrope text-[11px] font-extrabold uppercase tracking-[.14em] text-brandmidblue">
            Scenarios
          </span>
          <h2 className="mt-0.5 font-manrope text-2xl font-extrabold tracking-tight text-brandblue">
            Retrofit scenarios
          </h2>
          <div
            className="mt-3 h-[3px] max-w-[340px] rounded-full"
            style={{
              background:
                "linear-gradient(to right,#14163d 0%,#3943b7 34%,rgba(57,67,183,0) 90%)",
            }}
          />
        </div>
        <div className="flex flex-none items-center gap-2.5">
          {scenarios.length > 0 && (
            <Link
              href={`/portfolio/${slug}/modelling/run`}
              className="rounded-xl border border-gray-200 bg-white px-4 py-2.5 text-sm font-semibold text-brandblue transition hover:bg-gray-50"
            >
              Run modelling
            </Link>
          )}
          <Link
            href={`/portfolio/${slug}/scenarios/new`}
            className="rounded-xl px-4 py-2.5 text-sm font-semibold text-white shadow-[0_2px_10px_rgba(57,67,183,.35)] transition hover:shadow-[0_4px_16px_rgba(57,67,183,.45)]"
            style={{ background: "linear-gradient(135deg,#3943b7,#2d348f)" }}
          >
            + New scenario
          </Link>
        </div>
      </div>
      <p className="mb-6 max-w-[62ch] text-sm text-gray-600">
        Each scenario is a question you ask the modelling engine. Its
        configuration is fixed once created — rename any time; a different
        question is a new scenario.
      </p>

      {scenarios.length === 0 ? (
        <div className="mx-auto mt-9 max-w-[560px] rounded-2xl border-[1.5px] border-dashed border-gray-200 bg-white px-6 py-14 text-center">
          <div className="mb-5 inline-flex gap-1">
            {["G", "F", "E", "D", "C", "B", "A"].map((b) => (
              <span
                key={b}
                className="inline-block h-[7px] w-[26px] rounded-full"
                style={{ background: EPC_SOFT[b] }}
              />
            ))}
          </div>
          <h3 className="mb-2 font-manrope text-lg font-extrabold text-brandblue">
            No scenarios yet
          </h3>
          <p className="mx-auto mb-5 max-w-[44ch] text-sm text-gray-600">
            A scenario asks the modelling engine a question — “what does it
            take to reach EPC C?” Create your first and the answers appear in
            Reporting.
          </p>
          <Link
            href={`/portfolio/${slug}/scenarios/new`}
            className="inline-block rounded-xl px-4 py-2.5 text-sm font-semibold text-white"
            style={{ background: "linear-gradient(135deg,#3943b7,#2d348f)" }}
          >
            Create your first scenario
          </Link>
        </div>
      ) : (
        <div className="grid grid-cols-[repeat(auto-fill,minmax(330px,1fr))] gap-4">
          {scenarios.map((s) => {
            const isEpc = s.goal === PORTFOLIO_GOALS.EPC && s.goalValue;
            return (
              <Link
                key={String(s.id)}
                href={`/portfolio/${slug}/scenarios/${s.id}`}
                className="relative flex flex-col gap-3 overflow-hidden rounded-2xl border border-gray-100 bg-white p-5 pb-4 shadow-sm transition hover:-translate-y-0.5 hover:shadow-[0_10px_28px_rgba(20,22,61,.10)]"
              >
                <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 flex items-center gap-3">
                  {isEpc ? <BandChip band={s.goalValue!} /> : <GoalIcon />}
                  <div className="min-w-0">
                    <h3 className="truncate font-manrope text-base font-bold text-brandblue">
                      {s.name ?? `Scenario ${s.id}`}
                    </h3>
                    <div className="text-[13px] text-gray-600">
                      {isEpc
                        ? `Target EPC ${s.goalValue}`
                        : GOAL_SHORT_LABELS[s.goal] ?? s.goal}{" "}
                      · {s.housingType}
                    </div>
                  </div>
                </div>
                <div className="h-1 overflow-hidden rounded-full bg-gray-100">
                  <i
                    className="block h-full rounded-full"
                    style={
                      isEpc
                        ? { width: meterWidth(s.goalValue!), background: meterGradient(s.goalValue!) }
                        : { width: "100%", background: "linear-gradient(to right,#14163d,#3943b7)" }
                    }
                  />
                </div>
                <div className="relative rounded-xl border border-gray-100 bg-gray-50 px-3 py-2 text-[13px] text-gray-600">
                  {constraintLine(s.exclusions)}
                  {s.budget ? (
                    <>
                      {" "}
                      · <b className="font-semibold text-brandblue">{formatMoney(s.budget)}</b>
                      /property cap
                    </>
                  ) : null}
                  {s.fabricFirst ? (
                    <>
                      {" "}
                      · <FabricFirstChip className="align-middle" />
                    </>
                  ) : null}
                </div>
                <div className="relative flex items-center justify-between text-xs tabular-nums text-gray-400">
                  <StatusPill status={s.status} />
                  <span>
                    {s.status === "modelled"
                      ? `${s.plansCount.toLocaleString("en-GB")} properties · `
                      : ""}
                    Created {formatDate(s.createdAt)}
                  </span>
                </div>
              </Link>
            );
          })}
        </div>
      )}
    </div>
  );
}
