import { createFileRoute } from "@tanstack/react-router";
import { lazy, Suspense, useMemo, useState } from "react";
import { AppShell } from "@/components/AppShell";

const TrendChartBody = lazy(() => import("@/components/TrendChartBody"));
import { SectionHeader } from "@/components/SectionHeader";
import {
  useActivityComparison,
  useOperatorActivity,
} from "@/hooks/use-gridpath";
import { useFuelMixTrends, type FuelMixDay } from "@/hooks/use-fuel-mix-trends";
import { useAuth } from "@/hooks/use-auth";
import { useProfile } from "@/hooks/use-profile";
import { useLocationInsight } from "@/hooks/use-location-insight";
import { regionToBa } from "@/lib/gridpath";
import { resolveDefaultBa } from "@/lib/default-region";
import type {
  ActivityComparisonRegion,
  MoerBand,
  OperatorActivity,
} from "@/lib/gridpath";

const DEFAULT_BAS = [
  "ERCO",
  "CISO",
  "PJM",
  "NYIS",
  "MISO",
  "ISNE",
  "SPP",
  "BPAT",
  "TVA",
  "DUK",
  "FPL",
  "SOCO",
];

export const Route = createFileRoute("/dashboard")({
  head: () => ({
    meta: [
      { title: "Regional Activity — Quiet Hours" },
      {
        name: "description",
        content:
          "Operator-derived activity across multiple grid regions, with honest trends from GridPath.",
      },
      { property: "og:title", content: "Regional Activity Dashboard" },
      {
        property: "og:description",
        content: "Compare grid regions and see real trends — not fabricated lines.",
      },
    ],
  }),
  component: DashboardPage,
});

const bandStyle: Record<MoerBand, { bg: string; fg: string; label: string; plain: string }> = {
  clean: {
    bg: "oklch(0.74 0.13 145 / 0.18)",
    fg: "oklch(0.45 0.13 145)",
    label: "Cleaner",
    plain: "Power right now is coming from cleaner sources than usual.",
  },
  average: {
    bg: "oklch(0.78 0.13 65 / 0.18)",
    fg: "oklch(0.45 0.13 65)",
    label: "Average",
    plain: "Power right now is about as clean as a typical hour.",
  },
  dirty: {
    bg: "oklch(0.62 0.14 35 / 0.20)",
    fg: "oklch(0.45 0.14 35)",
    label: "Dirtier",
    plain:
      "Power right now is coming from dirtier sources than usual — a good time to wait if you can.",
  },
  unknown: {
    bg: "oklch(0.7 0.02 60 / 0.18)",
    fg: "oklch(0.45 0.02 60)",
    label: "Unknown",
    plain: "We don't have a fresh reading for this region yet.",
  },
};

const REGION_PLAIN: Record<string, string> = {
  ERCO: "Texas — most of the state's grid.",
  CISO: "California — most of the state's grid.",
  PJM: "Mid-Atlantic and parts of the Midwest (PA, NJ, OH, VA, and neighbors).",
  NYIS: "New York State.",
  MISO: "Central U.S., from the Dakotas down to Louisiana.",
  ISNE: "New England (CT, MA, ME, NH, RI, VT).",
  SPP: "Great Plains — KS, OK, NE, the Dakotas, and eastern Colorado.",
  BPAT: "Pacific Northwest — Oregon, Washington, Idaho, and parts of Montana.",
  TVA: "Tennessee Valley — TN, parts of KY, AL, MS, GA, NC, VA.",
  DUK: "The Carolinas — most of NC and SC.",
  FPL: "Florida — most of the state.",
  SOCO: "Southern Co. — Georgia, Alabama, parts of Mississippi.",
};

function DashboardPage() {
  const { user } = useAuth();
  const { profile } = useProfile(user?.id);
  const { insight } = useLocationInsight();

  // Priority: explicit click on a region card > live location entry on Home
  // > saved profile region > timezone hint > final fallback. Live location
  // wins over saved profile so a user changing their location anywhere in
  // the app immediately re-tailors this page.
  const savedBa = regionToBa(profile?.home_region ?? null);
  const liveBa = regionToBa(insight?.region ?? null);

  const comparison = useActivityComparison(DEFAULT_BAS);
  const [focusedBa, setFocusedBa] = useState<string | null>(null);

  const effectiveFocused =
    focusedBa ?? liveBa ?? savedBa ?? resolveDefaultBa(profile?.home_region ?? null) ?? "ERCO";

  const focusedRegion = useMemo<ActivityComparisonRegion | undefined>(
    () => comparison.data?.regions.find((r) => r.ba === effectiveFocused),
    [comparison.data, effectiveFocused],
  );
  const focusedName = focusedRegion?.ba_name ?? effectiveFocused;

  const trends = useFuelMixTrends(effectiveFocused, 30);
  const operator = useOperatorActivity(effectiveFocused);

  return (
    <AppShell>
      <SectionHeader
        eyebrow="Dashboard · multi-region"
        title="Regional Activity"
        sub="Operator-derived signals across major U.S. grid regions. Trends only appear when real snapshots exist — we don't fabricate history."
      />

      {/* A) Regions right now */}
      <section className="px-6">
        <div className="text-[11px] uppercase tracking-[0.18em] text-muted-foreground mb-1">
          Regions right now
        </div>
        <p className="text-sm text-muted-foreground mb-4 leading-relaxed">
          Each card below is one of the big U.S. power grids. Tap one to see how it's been doing
          this week and what its operator is talking about.
        </p>
        {comparison.isLoading && (
          <div className="text-sm text-muted-foreground">Loading regional snapshot…</div>
        )}
        {comparison.error && (
          <div className="text-sm text-muted-foreground">
            Couldn't reach GridPath right now. Try again in a moment.
          </div>
        )}
        {comparison.data && (
          <ul className="space-y-3">
            {comparison.data.regions.map((r) => {
              const isFocused = r.ba === effectiveFocused;
              const band = (r.moer?.band ?? "unknown") as MoerBand;
              const chip = bandStyle[band];
              const hasMoer = band !== "unknown";
              const cleanGw =
                r.queue?.clean_capacity_mw != null
                  ? (r.queue.clean_capacity_mw / 1000).toFixed(1)
                  : null;
              const out = r.outages?.customers_out ?? 0;
              const where = REGION_PLAIN[r.ba];
              return (
                <li key={r.ba}>
                  <button
                    onClick={() => setFocusedBa(r.ba)}
                    className={`w-full text-left bg-card border rounded-3xl p-5 transition ${
                      isFocused
                        ? "border-foreground/40"
                        : "border-border hover:border-foreground/25"
                    }`}
                    style={{ boxShadow: "var(--shadow-soft)" }}
                  >
                    <div className="flex items-start justify-between gap-3">
                      <div className="min-w-0">
                        <div className="font-serif text-lg leading-tight">{r.ba_name}</div>
                        {where && (
                          <div className="text-xs text-muted-foreground mt-1 leading-snug">
                            {where}
                          </div>
                        )}
                      </div>
                      {hasMoer && (
                        <span
                          className="text-[10px] uppercase tracking-wider px-2 py-1 rounded-full shrink-0"
                          style={{ background: chip.bg, color: chip.fg }}
                        >
                          {chip.label}
                        </span>
                      )}
                    </div>

                    {hasMoer && (
                      <p className="text-xs text-muted-foreground mt-3 leading-relaxed">
                        {chip.plain}
                      </p>
                    )}

                    <div className="mt-4 grid grid-cols-2 gap-4 text-xs">
                      <div>
                        <div className="text-muted-foreground uppercase tracking-wider text-[10px]">
                          Power outages
                        </div>
                        <div className="font-serif text-base mt-0.5 tabular-nums">
                          {out > 0 ? `${out.toLocaleString()} homes` : "None reported"}
                        </div>
                        <div className="text-[11px] text-muted-foreground mt-1 leading-snug">
                          Homes currently without power in this region.
                        </div>
                      </div>
                      <div>
                        <div className="text-muted-foreground uppercase tracking-wider text-[10px]">
                          Clean power coming
                        </div>
                        <div className="font-serif text-base mt-0.5 tabular-nums">
                          {cleanGw ? `${cleanGw} GW` : "—"}
                        </div>
                        <div className="text-[11px] text-muted-foreground mt-1 leading-snug">
                          Solar, wind, and battery projects waiting to plug in.
                        </div>
                      </div>
                    </div>

                    {!hasMoer && (
                      <p className="text-[11px] text-muted-foreground mt-4 leading-snug italic">
                        Live cleanliness signal not connected for this region yet — queue and
                        outage figures above are real.
                      </p>
                    )}
                  </button>
                </li>
              );
            })}
          </ul>
        )}
      </section>

      {/* B) Trends */}
      <section className="px-6 mt-10">
        <div className="text-[11px] uppercase tracking-[0.18em] text-muted-foreground mb-1">
          Trends in {focusedName} · last 30 days
        </div>
        <p className="text-sm text-muted-foreground mb-4 leading-relaxed">
          How the selected region's grid has been behaving day to day.
        </p>
        <TrendsBlock trends={trends.data} loading={trends.isLoading} />
      </section>

      {/* C) Operator activity */}
      <section className="px-6 mt-10">
        <div className="text-[11px] uppercase tracking-[0.18em] text-muted-foreground mb-1">
          What's happening in {focusedName}
        </div>
        <p className="text-sm text-muted-foreground mb-4 leading-relaxed">
          Recent notices from the people who run this grid — alerts, market updates, and planning
          news.
        </p>
        <OperatorBlock data={operator.data} loading={operator.isLoading} />
      </section>

      {/* Disclaimer + source */}
      <section className="px-6 mt-10 mb-4">
        {comparison.data?.disclaimer && (
          <p className="text-xs italic text-muted-foreground leading-relaxed">
            {comparison.data.disclaimer}
          </p>
        )}
        <p className="text-xs text-muted-foreground mt-2">
          Live signals via{" "}
          <a
            href="https://gridpath-insight.lovable.app"
            target="_blank"
            rel="noreferrer noopener"
            className="underline hover:text-foreground"
          >
            gridpath-insight
          </a>
          . Trends from the{" "}
          <a
            href="https://www.eia.gov/opendata/"
            target="_blank"
            rel="noreferrer noopener"
            className="underline hover:text-foreground"
          >
            U.S. EIA hourly grid data
          </a>
          .
        </p>
      </section>
    </AppShell>
  );
}

function TrendsBlock({
  trends,
  loading,
}: {
  trends: FuelMixDay[] | undefined;
  loading: boolean;
}) {
  if (loading) {
    return <div className="text-sm text-muted-foreground">Loading trends…</div>;
  }
  const series = trends ?? [];

  if (series.length < 2) {
    return (
      <div
        className="bg-card border border-border rounded-3xl p-6 text-center"
        style={{ boxShadow: "var(--shadow-soft)" }}
      >
        <div className="font-serif text-base leading-snug">
          Trend data is still syncing
        </div>
        <p className="text-xs text-muted-foreground mt-2 leading-relaxed max-w-[36ch] mx-auto">
          Daily fuel-mix snapshots from the U.S. Energy Information Administration are being
          backfilled for this region. Check back shortly.
        </p>
      </div>
    );
  }

  const data = series.map((p) => ({
    ts: p.day,
    label: new Date(p.day).toLocaleDateString([], { month: "numeric", day: "numeric" }),
    pct_clean: p.pct_clean != null ? Number(p.pct_clean) : null,
    mwh_total: p.mwh_total != null ? Number(p.mwh_total) : null,
  }));

  return (
    <div className="grid grid-cols-1 gap-4">
      <TrendChart
        title="% clean power"
        subtitle="Share of daily generation from wind, solar, hydro, and nuclear"
        data={data}
        dataKey="pct_clean"
        color="oklch(0.55 0.13 145)"
        unit="%"
      />
      <TrendChart
        title="Total daily generation"
        subtitle="Megawatt-hours produced across the region"
        data={data}
        dataKey="mwh_total"
        color="oklch(0.55 0.14 50)"
      />
    </div>
  );
}

function TrendChart({
  title,
  subtitle,
  data,
  dataKey,
  color,
  unit,
  sample = false,
}: {
  title: string;
  subtitle: string;
  data: Array<{ label: string; ts: string } & Record<string, unknown>>;
  dataKey: string;
  color: string;
  unit?: string;
  sample?: boolean;
}) {
  return (
    <div
      className="bg-card border border-border rounded-3xl p-5"
      style={{ boxShadow: "var(--shadow-soft)" }}
    >
      <div className="flex items-start justify-between gap-3">
        <div className="min-w-0">
          <div className="text-[15px] font-medium">{title}</div>
          <div className="text-xs text-muted-foreground mt-0.5">{subtitle}</div>
        </div>
        {sample && (
          <span className="inline-flex shrink-0 rounded-full px-2 py-0.5 text-[9px] font-medium uppercase tracking-wider bg-secondary text-muted-foreground">
            Sample
          </span>
        )}
      </div>
      <div className="h-40 mt-4">
        <Suspense fallback={<div className="h-full w-full rounded-xl bg-muted/40" />}>
          <TrendChartBody data={data} dataKey={dataKey} color={color} unit={unit} />
        </Suspense>
      </div>
    </div>
  );
}

function OperatorBlock({
  data,
  loading,
}: {
  data: OperatorActivity | undefined;
  loading: boolean;
}) {
  if (loading) return <div className="text-sm text-muted-foreground">Loading operator feed…</div>;
  if (!data) return null;
  const items = Array.isArray(data.items) ? data.items : [];
  if (items.length === 0) {
    return (
      <ul className="space-y-3">
        <li
          className="bg-card border border-border rounded-2xl p-4 opacity-95"
          style={{ boxShadow: "var(--shadow-soft)" }}
        >
          <div className="flex items-start justify-between gap-3">
            <div className="text-[15px] font-medium leading-snug">
              Evening peak demand expected between 6–9 PM
            </div>
            <span className="inline-flex shrink-0 rounded-full px-2 py-0.5 text-[9px] font-medium uppercase tracking-wider bg-secondary text-muted-foreground">
              Sample
            </span>
          </div>
          <div className="text-xs text-muted-foreground mt-1.5 leading-relaxed">
            Operators typically post a load forecast and conservation notice when summer heat or
            wind drop-offs raise reserve margins. Real notices will appear here as soon as the
            upstream feed for {data.ba_name} returns entries.
          </div>
          <div className="text-[10px] text-muted-foreground mt-2 uppercase tracking-wider">
            Representative example
          </div>
        </li>
      </ul>
    );
  }
  return (
    <ul className="space-y-3">
      {items.slice(0, 8).map((item, i) => (
        <li
          key={`${item.title}-${i}`}
          className="bg-card border border-border rounded-2xl p-4"
          style={{ boxShadow: "var(--shadow-soft)" }}
        >
          <div className="flex items-start justify-between gap-3">
            <div className="text-[15px] font-medium leading-snug">
              {item.url ? (
                <a
                  href={item.url}
                  target="_blank"
                  rel="noreferrer noopener"
                  className="hover:underline"
                >
                  {item.title}
                </a>
              ) : (
                item.title
              )}
            </div>
            {item.category && (
              <span className="text-[10px] uppercase tracking-wider px-2 py-0.5 rounded-full bg-secondary text-muted-foreground shrink-0">
                {item.category}
              </span>
            )}
          </div>
          {item.detail && (
            <div className="text-xs text-muted-foreground mt-1.5 leading-relaxed">
              {item.detail}
            </div>
          )}
          {item.published_at && (
            <div className="text-[10px] text-muted-foreground mt-2 uppercase tracking-wider">
              {new Date(item.published_at).toLocaleString([], {
                month: "short",
                day: "numeric",
                hour: "numeric",
                minute: "2-digit",
              })}
            </div>
          )}
        </li>
      ))}
    </ul>
  );
}
