import { createFileRoute, Link } from "@tanstack/react-router";
import { AppShell } from "@/components/AppShell";
import { SectionHeader } from "@/components/SectionHeader";
import cityTokyo from "@/assets/city-tokyo.webp";
import cityRio from "@/assets/city-rio.webp";
import {
  Thermometer,
  Wind,
  Home as HomeIcon,
  Building2,
  CalendarDays,
  Database,
  Leaf,
} from "@/lib/icons";
import {
  sourceCatalog,
  timelineSignals,
  tonightActions,
  tonightSnapshot,
  whyTonightDrivers,
} from "@/lib/quiet-hours-data";
import { useLocationInsight } from "@/hooks/use-location-insight";
import type { LocationInsight } from "@/lib/location-insights";
import { LiveGridSignalCard } from "@/components/LiveGridSignalCard";
import { CommunityShiftingBanner } from "@/components/CommunityShiftingBanner";
import { LiveOpportunityDot } from "@/components/LiveOpportunityDot";

export const Route = createFileRoute("/tonight")({
  head: () => ({
    meta: [
      { title: "Tonight — Quiet Hours" },
      {
        name: "description",
        content: "What's happening on the grid tonight, why, and the small shifts that help most.",
      },
      { property: "og:title", content: "Tonight on the grid" },
      {
        property: "og:description",
        content: "When many homes use more power at once, the system works harder.",
      },
      { property: "og:image", content: cityTokyo },
    ],
  }),
  component: TonightPage,
});

const driverIcon = {
  weather: Thermometer,
  wind: Wind,
  routine: HomeIcon,
  commercial: Building2,
} as const;

const sourceName = Object.fromEntries(sourceCatalog.map((source) => [source.id, source.name]));

function TonightPage() {
  const { insight } = useLocationInsight();
  const isDefaultRegion = !insight || insight.region === tonightSnapshot.region;
  const pageEyebrow = insight
    ? `Tonight · ${insight.label} · ${insight.gridName}`
    : "Tonight · set your area";
  const pageTitle = insight ? `Tonight in ${insight.label}` : "What's happening tonight";
  const pageSub = insight
    ? "Local grid context first, with recommendations kept honest about which public sources apply."
    : "Set your area on Home to tune this page to your local grid and weather context.";

  return (
    <AppShell>
      <SectionHeader eyebrow={pageEyebrow} title={pageTitle} sub={pageSub} />

      <LiveGridSignalCard region={insight?.region ?? null} />

      <CommunityShiftingBanner region={insight?.region ?? null} label={insight?.label} />

      {insight && !isDefaultRegion && <LocalSourceContext insight={insight} />}

      {/* Timeline */}
      {isDefaultRegion && (
        <section className="px-6">
          <div
            className="bg-card border border-border rounded-3xl p-5 animate-fade-rise"
            style={{ boxShadow: "var(--shadow-soft)" }}
          >
            <svg viewBox="0 0 320 140" className="w-full h-36">
              <defs>
                <linearGradient id="demandGrad" x1="0" x2="0" y1="0" y2="1">
                  <stop offset="0%" stopColor="oklch(0.78 0.13 65)" stopOpacity="0.5" />
                  <stop offset="100%" stopColor="oklch(0.78 0.13 65)" stopOpacity="0" />
                </linearGradient>
              </defs>
              {(() => {
                const pts = timelineSignals.map((p, i) => {
                  const x = (i / (timelineSignals.length - 1)) * 300 + 10;
                  const y = 130 - p.level * 110;
                  return [x, y] as const;
                });
                const path = pts.map(([x, y], i) => `${i === 0 ? "M" : "L"}${x},${y}`).join(" ");
                const area = `${path} L310,130 L10,130 Z`;
                return (
                  <>
                    <path d={area} fill="url(#demandGrad)" />
                    <path
                      d={path}
                      fill="none"
                      stroke="oklch(0.55 0.14 50)"
                      strokeWidth="2.5"
                      strokeLinecap="round"
                      className="animate-line-draw"
                    />
                    {pts.map(([x, y], i) => (
                      <g key={i}>
                        <circle
                          cx={x}
                          cy={y}
                          r="4"
                          fill="var(--background)"
                          stroke={timelineSignals[i].color}
                          strokeWidth="2"
                        />
                      </g>
                    ))}
                  </>
                );
              })()}
            </svg>
            <div className="grid grid-cols-5 gap-1 mt-2">
              {timelineSignals.map((t) => (
                <div key={t.time} className="text-center">
                  <div className="text-[10px] uppercase tracking-wider text-muted-foreground">
                    {t.time}
                  </div>
                </div>
              ))}
            </div>
          </div>

          <ul className="mt-5 space-y-3">
            {timelineSignals.map((t, i) => (
              <li
                key={t.time}
                className={`flex items-start gap-4 animate-fade-rise delay-${Math.min(i + 1, 5)}`}
              >
                <div className="w-14 text-sm font-medium tabular-nums">{t.time}</div>
                <div className="flex-1">
                  <div className="text-[15px]">{t.label}</div>
                </div>
                <div className="h-2 w-16 rounded-full bg-muted overflow-hidden mt-2">
                  <div
                    className="h-full rounded-full"
                    style={{ width: `${t.level * 100}%`, background: t.color }}
                  />
                </div>
              </li>
            ))}
          </ul>
        </section>
      )}

      {/* Why tonight — narrative drivers */}
      {isDefaultRegion && (
        <section className="px-6 mt-12">
          <div className="text-[11px] uppercase tracking-[0.18em] text-muted-foreground mb-4 animate-fade-rise">
            Why tonight
          </div>
          <ul className="space-y-3">
            {whyTonightDrivers.map((d, i) => {
              const Icon = driverIcon[d.icon];
              return (
                <li
                  key={d.id}
                  className={`bg-card border border-border rounded-3xl p-5 flex items-start gap-4 animate-fade-rise delay-${Math.min(i + 1, 5)}`}
                  style={{ boxShadow: "var(--shadow-soft)" }}
                >
                  <div className="h-11 w-11 rounded-2xl bg-secondary flex items-center justify-center shrink-0">
                    <Icon className="h-5 w-5 text-foreground/70" strokeWidth={1.6} />
                  </div>
                  <div>
                    <div className="text-[15px] font-medium">{d.title}</div>
                    <div className="text-sm text-muted-foreground mt-1 leading-relaxed">
                      {d.detail}
                    </div>
                  </div>
                </li>
              );
            })}
          </ul>
        </section>
      )}

      {isDefaultRegion && (
        <section className="px-6 mt-8">
          <div
            className="bg-card border border-border rounded-3xl p-5 text-sm text-muted-foreground"
            style={{ boxShadow: "var(--shadow-soft)" }}
          >
            <div>Weather driver: {tonightSnapshot.weatherSummary}</div>
            <div className="mt-2">
              Wholesale price trend: ${tonightSnapshot.wholesalePriceNow}/MWh now → $
              {tonightSnapshot.wholesalePricePeak}/MWh during peak window.
            </div>
            <div className="mt-2">
              Estimated demand ramp: {tonightSnapshot.demandRampMw.toLocaleString()} MW · renewable
              drop: {tonightSnapshot.renewableDropPct}%.
            </div>
          </div>
        </section>
      )}

      {isDefaultRegion && (
        <section className="px-6 mt-8">
          <div className="grid grid-cols-2 gap-3">
            <div
              className="bg-card border border-border rounded-3xl p-5 animate-fade-rise delay-2"
              style={{ boxShadow: "var(--shadow-soft)" }}
            >
              <div className="text-[11px] uppercase tracking-[0.18em] text-muted-foreground inline-flex items-center gap-1.5">
                <Database className="h-3 w-3" /> Stress score
              </div>
              <div className="font-serif text-3xl mt-2 tabular-nums">
                {tonightSnapshot.stressScore}/100
              </div>
              <p className="text-xs text-muted-foreground mt-2 leading-relaxed">
                Demand ramp, renewable drop, and price spread combined.
              </p>
            </div>
            <div
              className="bg-card border border-border rounded-3xl p-5 animate-fade-rise delay-3"
              style={{ boxShadow: "var(--shadow-soft)" }}
            >
              <div className="text-[11px] uppercase tracking-[0.18em] text-muted-foreground inline-flex items-center gap-1.5">
                <Leaf className="h-3 w-3" /> CO2 context
              </div>
              <div className="font-serif text-3xl mt-2 tabular-nums">
                {tonightSnapshot.avoidedEmissionsLbsCo2.toFixed(1)}{" "}
                <span className="text-base">lb</span>
              </div>
              <p className="text-xs text-muted-foreground mt-2 leading-relaxed">
                Estimated from annual eGRID factors, not live marginal dispatch.
              </p>
            </div>
          </div>
        </section>
      )}

      {/* What helps */}
      <section className="px-6 mt-10">
        <div className="text-[11px] uppercase tracking-[0.18em] text-muted-foreground mb-4">
          {insight ? `What helps most in ${insight.label}` : "What helps most"}
        </div>
        <ul className="space-y-3">
          {tonightActions.map((h, i) => (
            <li
              key={h.title}
              className={`bg-card border border-border rounded-2xl p-4 flex items-center justify-between animate-fade-rise delay-${Math.min(i + 1, 5)}`}
              style={{ boxShadow: "var(--shadow-soft)" }}
            >
              <div>
                <div className="flex items-center gap-2">
                  {h.impactBand === "High" && <LiveOpportunityDot />}
                  <div className="text-[15px] font-medium">{h.title}</div>
                </div>
                <div className="text-xs text-muted-foreground mt-0.5">{`${h.impactBand} impact · ${h.estimatedShiftKwh.toFixed(1)} kWh · $${h.estimatedSavingsUsd.toFixed(2)} est.`}</div>
                <div className="text-[11px] text-muted-foreground mt-1 leading-relaxed">
                  {h.assumption}
                </div>
              </div>
              <span
                className={`text-[10px] uppercase tracking-wider px-2.5 py-1 rounded-full ${
                  h.impactBand === "High"
                    ? "bg-sage/20 text-foreground"
                    : "bg-secondary text-muted-foreground"
                }`}
              >
                {h.impactBand}
              </span>
            </li>
          ))}
        </ul>
      </section>

      {isDefaultRegion && (
        <section className="px-6 mt-10">
          <div className="text-[11px] uppercase tracking-[0.18em] text-muted-foreground mb-4">
            Evidence used tonight
          </div>
          <ul className="space-y-3">
            {tonightSnapshot.evidence.map((item, i) => (
              <li
                key={`${item.sourceId}-${item.metric}`}
                className={`bg-card border border-border rounded-2xl p-4 animate-fade-rise delay-${Math.min(i + 1, 5)}`}
                style={{ boxShadow: "var(--shadow-soft)" }}
              >
                <div className="flex items-start justify-between gap-4">
                  <div>
                    <div className="text-[15px] font-medium">{item.metric}</div>
                    <div className="text-xs text-muted-foreground mt-1">
                      {sourceName[item.sourceId]} ·{" "}
                      {new Date(item.observedAt).toLocaleTimeString([], {
                        hour: "numeric",
                        minute: "2-digit",
                      })}
                    </div>
                  </div>
                  <div className="font-serif text-xl tabular-nums text-right">{item.value}</div>
                </div>
                <p className="text-xs text-muted-foreground mt-3 leading-relaxed">{item.note}</p>
              </li>
            ))}
          </ul>
        </section>
      )}

      <section className="px-6 mt-8">
        <Link
          to="/forecast"
          className="block overflow-hidden rounded-3xl bg-card border border-border hover:border-foreground/30 transition"
          style={{ boxShadow: "var(--shadow-soft)" }}
        >
          <div className="relative h-32 w-full overflow-hidden">
            <img
              src={cityRio}
              alt="Rio de Janeiro skyline at dusk"
              loading="lazy"
              decoding="async"
              className="absolute inset-0 h-full w-full object-cover"
            />
            <div
              className="absolute inset-0"
              style={{
                background:
                  "linear-gradient(180deg, oklch(0.18 0.03 60 / 0.15) 0%, oklch(0.18 0.03 60 / 0.55) 100%)",
              }}
              aria-hidden
            />
          </div>
          <div className="p-5">
            <div className="text-[11px] uppercase tracking-[0.18em] text-muted-foreground inline-flex items-center gap-1.5">
              <CalendarDays className="h-3 w-3" /> Look ahead
            </div>
            <div className="font-serif text-xl mt-2">Shared Hour Forecast</div>
            <div className="text-sm text-muted-foreground mt-1">
              A seven-day rhythm of the city's evening.
            </div>
          </div>
        </Link>
      </section>
    </AppShell>
  );
}

function LocalSourceContext({ insight }: { insight: LocationInsight }) {
  const sources = insight.sources
    .map((sourceId) => sourceCatalog.find((source) => source.id === sourceId)?.name)
    .filter(Boolean)
    .slice(0, 4);

  return (
    <section className="px-6 mt-3">
      <div
        className="rounded-3xl border border-border bg-card p-5 animate-fade-rise"
        style={{ boxShadow: "var(--shadow-soft)" }}
      >
        <div className="text-[11px] uppercase tracking-[0.18em] text-muted-foreground">
          Local source context
        </div>
        <div className="font-serif text-2xl leading-tight mt-2">
          {insight.gridName} guidance for {insight.label}
        </div>
        <p className="mt-3 text-sm leading-relaxed text-muted-foreground">
          This view uses the public sources available for your area and leaves out regional values
          that do not apply here. Utility territory data can make rates and program eligibility more
          precise.
        </p>
        <div className="mt-4 grid grid-cols-1 gap-2 sm:grid-cols-3">
          {insight.localDrivers.map((driver) => (
            <div key={driver} className="rounded-[4px] bg-secondary px-3 py-3 text-left">
              <div className="text-[11px] font-medium leading-snug text-foreground/85">
                {driver}
              </div>
              <div className="mt-1 text-[10px] leading-snug text-muted-foreground">
                {driverExplainer(driver)}
              </div>
            </div>
          ))}
        </div>
        {sources.length > 0 && (
          <div className="mt-4 text-[11px] uppercase tracking-wide text-muted-foreground">
            Sources: {sources.join(" + ")}
          </div>
        )}
      </div>
    </section>
  );
}

function driverExplainer(driver: string) {
  const explainers: Record<string, string> = {
    "Solar fade after sunset": "Less solar is available while homes are still active.",
    "Cooling load in inland neighborhoods": "Hotter areas keep air conditioners running later.",
    "Evening price spread": "Power can cost more during the tightest hours.",
    "Heat-driven cooling": "Air conditioning is usually the largest flexible load.",
    "Reserve margin": "The grid has less spare capacity when demand gets close to supply.",
    "Wind and solar variability": "Renewables can rise or fall quickly in the evening.",
    "Zonal load": "Demand differs by neighborhood and transmission zone.",
    "Real-time fuel mix": "The sources serving load can change hour by hour.",
    "Dense residential evening demand": "Many homes cook, cool, charge, and wash at once.",
    "Regional load forecast": "A public forecast estimates how heavy demand may get.",
    "Transmission constraints": "Some power lines can become bottlenecks during peak use.",
    "Peak price risk": "Higher prices can signal a tighter operating hour.",
    "Official local weather forecast": "Weather helps explain likely heating or cooling demand.",
    "Nearest balancing authority demand": "Federal data can anchor the nearest grid region.",
    "Representative residential load shapes": "Public models estimate typical home timing.",
    "Local timezone": "Recommendations should land in the right evening hours.",
    "Weather-driven timing": "Temperature and storms shape when demand is heavier.",
    "Country-specific grid data adapter": "Live grid claims need a trusted local source.",
  };

  return explainers[driver] ?? "A local signal that can affect evening demand.";
}
