/**
 * Scenario detail — params + the latest persisted MC projection.
 *
 * Reuses FanChart from the What-If page. If the scenario has no MC run
 * yet, prompts the user to run /recompute.
 */
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Link, useNavigate, useParams } from 'react-router-dom';

import { api, lifeEventsApi, type Scenario, type SimulateRequest } from '@/api/client';
import { ApiError } from '@/api/client';
import { FanChart } from '@/components/FanChart';
import { GoalsSection } from '@/components/GoalsSection';
import { LifeEventsSection } from '@/components/LifeEventsSection';
import { gbp, pct } from '@/lib/format';

export function ScenarioDetail() {
  const params = useParams<{ id: string }>();
  const id = Number(params.id);
  const navigate = useNavigate();
  const qc = useQueryClient();

  const scen = useQuery({
    queryKey: ['scenarios', id],
    queryFn: () => api.scenarios.get(id),
    enabled: Number.isFinite(id),
  });
  const proj = useQuery({
    queryKey: ['scenarios', id, 'projection'],
    queryFn: () => api.scenarios.projection(id),
    enabled: Number.isFinite(id),
    retry: (count, err) => {
      // Don't retry the 404 — it's the "no run yet" empty state.
      if (err instanceof ApiError && err.status === 404) return false;
      return count < 2;
    },
  });

  const del = useMutation({
    mutationFn: () => api.scenarios.delete(id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['scenarios'] });
      navigate('/scenarios');
    },
  });

  const sim = useMutation({
    mutationFn: (req: SimulateRequest) => api.simulate(req),
  });

  const onDelete = () => {
    if (!confirm(`Delete scenario "${scen.data?.name ?? id}"? This can't be undone.`)) return;
    del.mutate();
  };

  const onRunNow = async (s: Scenario) => {
    // Pull events fresh so the run reflects whatever the user just edited.
    const events = await lifeEventsApi.list(s.id);
    sim.mutate({
      jurisdiction: s.jurisdiction,
      strategy: s.strategy,
      leave_uk_year: s.leave_uk_year,
      spending_gbp: s.spending_gbp,
      nw_seed_gbp: s.nw_seed_gbp,
      savings_per_year_gbp: s.savings_per_year_gbp,
      horizon_years: s.horizon_years,
      n_paths: 5000,
      seed: 42,
      life_events: events.map((e) => ({
        year_start: e.year_start,
        year_end: e.year_end,
        delta_gbp_per_year: e.delta_gbp_per_year,
        one_time_amount_gbp: e.one_time_amount_gbp,
        enabled: e.enabled,
      })),
    });
  };

  if (!Number.isFinite(id)) {
    return <p className="text-red-700">Invalid scenario id.</p>;
  }

  if (scen.isLoading) return <p className="text-slate-500">Loading…</p>;
  if (scen.isError || !scen.data) {
    return (
      <div className="rounded-md border border-red-200 bg-red-50 p-4 text-red-800 text-sm">
        Couldn&apos;t load scenario {id}.
      </div>
    );
  }

  const s = scen.data;
  const projection = proj.data;
  const projection404 = proj.isError && proj.error instanceof ApiError && proj.error.status === 404;

  return (
    <section className="space-y-6">
      <div className="text-sm">
        <Link to="/scenarios" className="text-slate-500 hover:text-slate-900">
          ← Scenarios
        </Link>
      </div>

      <header className="flex items-start justify-between gap-4">
        <div>
          <h1 className="text-3xl font-semibold tracking-tight">{s.name ?? s.external_id}</h1>
          <p className="text-sm text-slate-500 mt-1">
            {s.kind} · {s.jurisdiction} · {s.strategy} · leave UK y{s.leave_uk_year} ·{' '}
            {s.glide_path} glide · {s.horizon_years}y horizon
          </p>
          {s.description && <p className="text-sm text-slate-600 mt-2">{s.description}</p>}
        </div>
        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={() => void onRunNow(s)}
            disabled={sim.isPending}
            className="rounded-md border border-slate-300 bg-white text-sm px-3 py-1.5 hover:bg-slate-50 disabled:opacity-60"
            title="Run a fresh MC including this scenario's life events"
          >
            {sim.isPending ? 'Running…' : 'Run now'}
          </button>
          {s.kind === 'user' && (
            <>
              <Link
                to={`/scenarios/${s.id}/edit`}
                className="rounded-md border border-slate-300 bg-white text-sm px-3 py-1.5 hover:bg-slate-50"
              >
                Edit
              </Link>
              <button
                type="button"
                onClick={onDelete}
                disabled={del.isPending}
                className="rounded-md border border-red-300 text-red-700 text-sm px-3 py-1.5 hover:bg-red-50 disabled:opacity-60"
              >
                {del.isPending ? 'Deleting…' : 'Delete'}
              </button>
            </>
          )}
        </div>
      </header>
      {del.isError && (
        <div className="rounded-md border border-red-200 bg-red-50 p-3 text-red-800 text-sm">
          {String((del.error as Error)?.message ?? del.error)}
        </div>
      )}

      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <Stat label="Spending" value={gbp(s.spending_gbp)} />
        <Stat label="NW seed" value={gbp(s.nw_seed_gbp)} />
        <Stat label="Annual savings" value={gbp(s.savings_per_year_gbp)} />
        <Stat label="Horizon" value={`${s.horizon_years}y`} />
      </div>

      {projection ? (
        <>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
            <Stat label="Success rate" value={pct(projection.success_rate)} accent />
            <Stat label="Median ending NW" value={gbp(projection.p50_ending_gbp)} />
            <Stat label="P10 ending" value={gbp(projection.p10_ending_gbp)} />
            <Stat label="P90 ending" value={gbp(projection.p90_ending_gbp)} />
            <Stat label="Median lifetime tax" value={gbp(projection.median_lifetime_tax_gbp)} />
            <Stat
              label="Median years to ruin"
              value={projection.median_years_to_ruin ?? 'never'}
            />
            <Stat label="MC paths" value={projection.n_paths.toLocaleString()} />
            <Stat label="Run at" value={new Date(projection.run_at).toLocaleString()} />
          </div>

          <div className="rounded-lg border border-slate-200 bg-white p-5">
            <h2 className="text-lg font-semibold mb-2">Portfolio fan</h2>
            <FanChart yearly={projection.yearly} height={420} showWithdrawal />
          </div>
        </>
      ) : projection404 ? (
        <div className="rounded-lg border border-slate-200 bg-white p-8 text-center text-slate-500">
          <p className="font-medium text-slate-700">No projection yet.</p>
          <p className="text-sm mt-2">
            Run <code className="px-1">python -m fire_planner recompute-all</code> or{' '}
            <code>POST /recompute</code> to fill in MC projections for all scenarios.
          </p>
        </div>
      ) : proj.isLoading ? (
        <p className="text-slate-500">Loading projection…</p>
      ) : (
        <div className="rounded-md border border-red-200 bg-red-50 p-4 text-red-800 text-sm">
          {String((proj.error as Error)?.message ?? proj.error)}
        </div>
      )}

      {sim.data && (
        <div className="rounded-lg border border-slate-200 bg-white p-5">
          <div className="flex items-baseline justify-between mb-3">
            <h2 className="text-lg font-semibold">Live preview run</h2>
            <span className="text-xs text-slate-500">
              {sim.data.elapsed_seconds}s · 5,000 paths · success {pct(sim.data.success_rate)}
            </span>
          </div>
          <FanChart yearly={sim.data.yearly} height={360} showWithdrawal />
        </div>
      )}
      {sim.isError && (
        <div className="rounded-md border border-red-200 bg-red-50 p-3 text-red-800 text-sm">
          {String((sim.error as Error)?.message ?? sim.error)}
        </div>
      )}

      <LifeEventsSection scenarioId={id} />
      <GoalsSection scenarioId={id} />
    </section>
  );
}

function Stat({
  label,
  value,
  accent,
}: {
  label: string;
  value: string | number;
  accent?: boolean;
}) {
  return (
    <div className="rounded-md border border-slate-200 bg-white p-3">
      <div className="text-xs uppercase tracking-wide text-slate-500">{label}</div>
      <div
        className={`text-xl font-semibold tabular-nums mt-1 ${
          accent ? 'text-emerald-700' : ''
        }`}
      >
        {value}
      </div>
    </div>
  );
}
