/**
 * Scenarios list — both Cartesian (engine-generated) and user-defined.
 * Filter chips at the top; each row links to a detail page.
 *
 * The Cartesian set is whatever the latest /recompute produced (default
 * 120 scenarios). User scenarios survive recomputes.
 */
import { useQuery } from '@tanstack/react-query';
import { Link } from 'react-router-dom';
import { useState } from 'react';

import { api, type Scenario } from '@/api/client';
import { gbp } from '@/lib/format';

type Filter = 'all' | 'cartesian' | 'user';

export function Scenarios() {
  const [filter, setFilter] = useState<Filter>('all');
  const scenarios = useQuery({
    queryKey: ['scenarios', filter],
    queryFn: () => api.scenarios.list(filter === 'all' ? undefined : filter),
  });

  return (
    <section className="space-y-6">
      <header className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-semibold tracking-tight">Scenarios</h1>
          <p className="text-sm text-slate-500">
            Persisted plans. Cartesian rebuilt from <code>/recompute</code>; user-defined survive.
          </p>
        </div>
        <FilterChips value={filter} onChange={setFilter} />
      </header>

      {scenarios.isLoading ? (
        <p className="text-slate-500">Loading…</p>
      ) : scenarios.isError ? (
        <ErrorBox error={scenarios.error} />
      ) : scenarios.data && scenarios.data.length > 0 ? (
        <ScenarioTable scenarios={scenarios.data} />
      ) : (
        <EmptyState filter={filter} />
      )}
    </section>
  );
}

function FilterChips({ value, onChange }: { value: Filter; onChange: (v: Filter) => void }) {
  const opts: { key: Filter; label: string }[] = [
    { key: 'all', label: 'All' },
    { key: 'cartesian', label: 'Cartesian' },
    { key: 'user', label: 'User' },
  ];
  return (
    <div className="inline-flex rounded-md border border-slate-200 bg-white p-0.5">
      {opts.map((o) => (
        <button
          key={o.key}
          type="button"
          onClick={() => onChange(o.key)}
          className={`px-3 py-1 text-sm rounded ${
            value === o.key
              ? 'bg-slate-900 text-white'
              : 'text-slate-600 hover:text-slate-900'
          }`}
        >
          {o.label}
        </button>
      ))}
    </div>
  );
}

function ScenarioTable({ scenarios }: { scenarios: Scenario[] }) {
  return (
    <div className="rounded-lg border border-slate-200 bg-white overflow-hidden">
      <table className="w-full text-sm">
        <thead className="bg-slate-50 text-slate-600 text-xs uppercase tracking-wide">
          <tr>
            <th className="text-left px-4 py-2">Name / ID</th>
            <th className="text-left px-4 py-2">Kind</th>
            <th className="text-left px-4 py-2">Jurisdiction</th>
            <th className="text-left px-4 py-2">Strategy</th>
            <th className="text-left px-4 py-2">Leave UK</th>
            <th className="text-left px-4 py-2">Glide</th>
            <th className="text-right px-4 py-2">Spending</th>
            <th className="text-right px-4 py-2">NW seed</th>
          </tr>
        </thead>
        <tbody>
          {scenarios.map((s) => (
            <tr key={s.id} className="border-t border-slate-100 hover:bg-slate-50">
              <td className="px-4 py-2">
                <Link to={`/scenarios/${s.id}`} className="text-blue-700 hover:underline">
                  {s.name ?? s.external_id}
                </Link>
                {s.name && (
                  <div className="text-xs text-slate-400">{s.external_id}</div>
                )}
              </td>
              <td className="px-4 py-2">
                <KindBadge kind={s.kind} />
              </td>
              <td className="px-4 py-2 capitalize">{s.jurisdiction}</td>
              <td className="px-4 py-2">{s.strategy}</td>
              <td className="px-4 py-2">y{s.leave_uk_year}</td>
              <td className="px-4 py-2">{s.glide_path}</td>
              <td className="px-4 py-2 text-right tabular-nums">{gbp(s.spending_gbp)}</td>
              <td className="px-4 py-2 text-right tabular-nums">{gbp(s.nw_seed_gbp)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function KindBadge({ kind }: { kind: Scenario['kind'] }) {
  const styles = kind === 'user' ? 'bg-emerald-100 text-emerald-800' : 'bg-slate-100 text-slate-600';
  return (
    <span className={`text-xs px-2 py-0.5 rounded ${styles}`}>{kind}</span>
  );
}

function EmptyState({ filter }: { filter: Filter }) {
  return (
    <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 scenarios{filter !== 'all' ? ` (${filter})` : ''}.</p>
      <p className="text-sm mt-2">
        Run <code className="px-1">python -m fire_planner recompute-all</code> to populate the
        Cartesian set, or create a user scenario via <code>POST /scenarios</code>.
      </p>
    </div>
  );
}

function ErrorBox({ error }: { error: unknown }) {
  return (
    <div className="rounded-md border border-red-200 bg-red-50 p-4 text-red-800 text-sm">
      {String((error as Error)?.message ?? error)}
    </div>
  );
}
