import Link from "next/link";
import { apiFetch } from "@/lib/api";
import type { ScenarioSummary } from "@/types/api";

async function getScenarios() {
  try {
    return await apiFetch<ScenarioSummary[]>("/api/scenarios");
  } catch {
    return [];
  }
}

function pct(v: number) {
  return `${Math.round(v * 100)}%`;
}

export default async function ScenariosPage() {
  const scenarios = await getScenarios();

  return (
    <div className="min-h-screen bg-stone-50">
      <div className="border-b border-stone-200 bg-white">
        <div className="mx-auto max-w-5xl px-4 py-5 sm:px-6 sm:py-6 lg:px-8">
          <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
            <div>
              <div className="mb-1.5 flex items-center gap-2 text-sm font-medium text-stone-500">
                <Link href="/" className="hover:text-stone-700">ACI Platform</Link>
                <span>/</span>
                <span>Scenarios</span>
              </div>
              <h1 className="text-lg sm:text-2xl font-bold tracking-tight text-stone-900">Saved Scenarios</h1>
              <p className="mt-1 text-xs sm:text-sm text-stone-500">
                All previously run simulations with their AI results.
              </p>
            </div>
            <Link
              href="/scenarios/new"
              className="inline-flex w-full items-center justify-center rounded-lg bg-emerald-800 px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-emerald-700 sm:w-auto"
            >
              New Scenario →
            </Link>
          </div>
        </div>
      </div>

      <div className="mx-auto max-w-5xl px-4 py-6 sm:px-6 sm:py-8 lg:px-8">
        {scenarios.length === 0 ? (
          <div className="flex flex-col items-center justify-center rounded-2xl border border-dashed border-stone-200 bg-white py-24 text-center">
            <div className="mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-emerald-50">
              <svg className="h-7 w-7 text-emerald-600" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" d="M9.75 3.104v5.714a2.25 2.25 0 0 1-.659 1.591L5 14.5M9.75 3.104c-.251.023-.501.05-.75.082m.75-.082a24.301 24.301 0 0 1 4.5 0m0 0v5.714c0 .597.237 1.17.659 1.591L19.8 15.3M14.25 3.104c.251.023.501.05.75.082M19.8 15.3l-1.57.393A9.065 9.065 0 0 1 12 15a9.065 9.065 0 0 1-6.23-.693L5 14.5m14.8.8 1.402 1.402c1.232 1.232.65 3.318-1.067 3.611A48.309 48.309 0 0 1 12 21a48.25 48.25 0 0 1-8.135-.687c-1.718-.293-2.3-2.379-1.067-3.61L5 14.5" />
              </svg>
            </div>
            <p className="text-sm font-medium text-stone-600">No scenarios yet</p>
            <p className="mt-1 text-xs text-stone-400">Run your first simulation to see results here.</p>
            <Link
              href="/scenarios/new"
              className="mt-5 rounded-lg bg-emerald-800 px-5 py-2.5 text-sm font-semibold text-white transition hover:bg-emerald-700"
            >
              Start New Scenario
            </Link>
          </div>
        ) : (
          <div className="space-y-3">
            {scenarios.map((s) => (
              <Link
                key={s.id}
                href={`/scenarios/${s.id}`}
                className="group flex flex-col gap-4 rounded-2xl border border-stone-200 bg-white p-4 transition-all hover:border-emerald-300 hover:shadow-xl active:scale-[0.98] sm:flex-row sm:items-center sm:gap-5 sm:p-6"
              >
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <p className="truncate text-base font-bold text-stone-900 group-hover:text-emerald-800 transition-colors">{s.name}</p>
                    <svg className="h-4 w-4 shrink-0 text-stone-300 group-hover:text-emerald-400 transition-colors sm:hidden" fill="none" viewBox="0 0 24 24" strokeWidth={2.5} stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" d="m8.25 4.5 7.5 7.5-7.5 7.5" />
                    </svg>
                  </div>
                  <p className="mt-1 text-xs capitalize text-stone-500 font-medium">
                    {s.season} · {s.duration_days} days ·{" "}
                    {new Date(s.created_at).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" })}
                  </p>
                </div>
                <div className="grid grid-cols-3 gap-3 border-t border-stone-100 pt-4 sm:flex sm:shrink-0 sm:items-center sm:justify-end sm:gap-8 sm:border-t-0 sm:pt-0">
                  {s.predicted_yield != null && (
                    <div className="text-left sm:text-right">
                      <p className="text-[10px] font-bold uppercase tracking-wider text-stone-400">Yield</p>
                      <p className="mt-0.5 text-sm font-bold text-stone-800">{s.predicted_yield.toFixed(2)}<span className="ml-0.5 text-[10px] text-stone-400 font-medium">kg</span></p>
                    </div>
                  )}
                  {s.survival_probability != null && (
                    <div className="text-left sm:text-right">
                      <p className="text-[10px] font-bold uppercase tracking-wider text-stone-400">Survival</p>
                      <p className={`mt-0.5 text-sm font-bold ${s.survival_probability >= 0.75 ? "text-emerald-600" : s.survival_probability >= 0.55 ? "text-amber-500" : "text-red-500"}`}>
                        {pct(s.survival_probability)}
                      </p>
                    </div>
                  )}
                  {s.confidence_score != null && (
                    <div className="text-left sm:text-right">
                      <p className="text-[10px] font-bold uppercase tracking-wider text-stone-400">Conf.</p>
                      <p className="mt-0.5 text-sm font-bold text-stone-700">{pct(s.confidence_score)}</p>
                    </div>
                  )}
                  <div className="hidden sm:block">
                    <svg className="h-5 w-5 shrink-0 text-stone-300 group-hover:translate-x-1 group-hover:text-emerald-500 transition-all" fill="none" viewBox="0 0 24 24" strokeWidth={2.5} stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" d="m8.25 4.5 7.5 7.5-7.5 7.5" />
                    </svg>
                  </div>
                </div>
              </Link>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
