import Link from "next/link";
import { notFound } from "next/navigation";
import { apiFetch } from "@/lib/api";
import type { Scenario } from "@/types/api";
import GrowthChart from "./_components/GrowthChart";

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function scoreColor(value: number, thresholds = [0.75, 0.55]) {
  if (value >= thresholds[0]) return "text-emerald-600";
  if (value >= thresholds[1]) return "text-amber-500";
  return "text-red-500";
}

function scoreBg(value: number, thresholds = [0.75, 0.55]) {
  if (value >= thresholds[0]) return "bg-emerald-50 border-emerald-200";
  if (value >= thresholds[1]) return "bg-amber-50 border-amber-200";
  return "bg-red-50 border-red-200";
}

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

function NpkBar({
  label,
  applied,
  recommended,
  unit = "kg/ha",
}: {
  label: string;
  applied: number;
  recommended: number;
  unit?: string;
}) {
  const max = Math.max(applied, recommended, 1) * 1.2;
  const appliedPct = (applied / max) * 100;
  const recPct = (recommended / max) * 100;
  const diff = recommended - applied;
  const diffPct = recommended > 0 ? Math.abs(diff / recommended) : 0;
  const status =
    diffPct <= 0.1 ? "optimal" : diff > 0 ? "increase" : "reduce";

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <span className="text-xs font-bold uppercase tracking-wider text-stone-600">{label}</span>
        <span
          className={`rounded-full px-2.5 py-1 text-[10px] font-bold uppercase tracking-wider ${
            status === "optimal"
              ? "bg-emerald-100 text-emerald-700"
              : status === "increase"
                ? "bg-blue-100 text-blue-700"
                : "bg-amber-100 text-amber-700"
          }`}
        >
          {status === "optimal"
            ? "Optimal"
            : status === "increase"
              ? `+${Math.abs(diff).toFixed(0)} ${unit}`
              : `-${Math.abs(diff).toFixed(0)} ${unit}`}
        </span>
      </div>
      <div className="space-y-2">
        <div>
          <div className="mb-1 flex items-center justify-between text-[10px] font-bold text-stone-400 uppercase">
            <span>Applied</span>
            <span className="text-stone-600">{applied} {unit}</span>
          </div>
          <div className="h-2 w-full rounded-full bg-stone-100 overflow-hidden">
            <div
              className="h-full rounded-full bg-stone-400 transition-all duration-1000"
              style={{ width: `${appliedPct}%` }}
            />
          </div>
        </div>
        <div>
          <div className="mb-1 flex items-center justify-between text-[10px] font-bold text-stone-400 uppercase">
            <span>Recommended</span>
            <span className="text-emerald-700">{recommended} {unit}</span>
          </div>
          <div className="h-2 w-full rounded-full bg-stone-100 overflow-hidden">
            <div
              className="h-full rounded-full bg-emerald-500 transition-all duration-1000"
              style={{ width: `${recPct}%` }}
            />
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Page
// ---------------------------------------------------------------------------

export default async function ScenarioResultPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;

  let scenario: Scenario;
  try {
    scenario = await apiFetch<Scenario>(`/api/scenarios/${id}`);
  } catch {
    notFound();
  }

  const results = scenario.results;
  const graft = scenario.graft_combination;
  const plant = scenario.plant ?? graft?.scion;
  const soil = scenario.soil_profile;
  const rec = results?.recommended_adjustments as Record<string, number & string> | undefined;

  return (
    <div className="min-h-screen bg-stone-50">
      {/* Header */}
      <div className="border-b border-stone-200 bg-white">
        <div className="mx-auto max-w-5xl px-4 py-4 sm:px-6 sm:py-6 lg:px-8">
          <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>
            <Link href="/scenarios" className="hover:text-stone-700">Scenarios</Link>
            <span>/</span>
            <span className="text-stone-900 truncate">{scenario.name}</span>
          </div>
          <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
            <div className="min-w-0">
              <h1 className="text-lg sm:text-2xl font-bold tracking-tight text-stone-900 break-words">
                {scenario.name}
              </h1>
              <p className="mt-1 text-xs sm:text-sm text-stone-500 capitalize">
                {scenario.season} · {scenario.duration_days} days ·{" "}
                {scenario.irrigation_method} irrigation
              </p>
            </div>
            <div className="flex gap-2 shrink-0">
              <Link
                href="/scenarios/compare"
                className="flex-1 sm:flex-none text-center rounded-lg border border-stone-200 bg-white px-4 py-2 text-sm font-medium text-stone-700 transition hover:bg-stone-50"
              >
                Compare
              </Link>
              <Link
                href="/scenarios/new"
                className="flex-1 sm:flex-none text-center rounded-lg bg-emerald-800 px-4 py-2 text-sm font-semibold text-white transition hover:bg-emerald-700"
              >
                New Scenario
              </Link>
            </div>
          </div>
        </div>
      </div>

      <div className="mx-auto max-w-5xl space-y-4 px-4 py-6 sm:space-y-6 sm:px-6 sm:py-8 lg:px-8">
        {!results ? (
          <div className="rounded-2xl border border-dashed border-stone-200 bg-white py-20 text-center">
            <p className="text-sm font-medium text-stone-500">Analysis not yet available.</p>
          </div>
        ) : (
          <>
            {/* ── Hero Metrics ───────────────────────────────────────── */}
            <div className="grid gap-4 grid-cols-1 sm:grid-cols-3">
              {[
                {
                  label: "Predicted Yield",
                  value: results.predicted_yield != null
                    ? `${results.predicted_yield.toFixed(2)} kg`
                    : "—",
                  sub: "per plant",
                  raw: results.predicted_yield ?? 0,
                  isYield: true,
                },
                {
                  label: "Survival Probability",
                  value: results.survival_probability != null
                    ? pct(results.survival_probability)
                    : "—",
                  sub: "estimated chance",
                  raw: results.survival_probability ?? 0,
                },
                {
                  label: "Confidence Score",
                  value: results.confidence_score != null
                    ? pct(results.confidence_score)
                    : "—",
                  sub: "AI confidence",
                  raw: results.confidence_score ?? 0,
                },
              ].map((m) => (
                <div
                  key={m.label}
                  className={`rounded-2xl border p-5 sm:p-6 ${m.isYield ? "bg-emerald-50 border-emerald-200" : scoreBg(m.raw)}`}
                >
                  <p className="text-[10px] sm:text-xs font-semibold uppercase tracking-wider text-stone-500">
                    {m.label}
                  </p>
                  <p
                    className={`mt-2 text-3xl sm:text-4xl font-bold tracking-tight ${
                      m.isYield ? "text-emerald-700" : scoreColor(m.raw)
                    }`}
                  >
                    {m.value}
                  </p>
                  <p className="mt-1 text-xs text-stone-500">{m.sub}</p>
                </div>
              ))}
            </div>

            {/* ── Plant + Soil Summary ────────────────────────────────── */}
            <div className="grid gap-4 grid-cols-1 sm:grid-cols-2">
              <div className="rounded-2xl border border-stone-200 bg-white p-5">
                <p className="mb-3 text-[10px] sm:text-xs font-semibold uppercase tracking-wider text-stone-400">
                  Plant Setup
                </p>
                <div className="space-y-2 text-xs sm:text-sm">
                  {plant && (
                    <div className="flex justify-between">
                      <span className="text-stone-500">Scion</span>
                      <span className="font-medium text-stone-900">{plant.name}</span>
                    </div>
                  )}
                  {graft ? (
                    <div className="flex justify-between">
                      <span className="text-stone-500">Rootstock</span>
                      <span className="font-medium text-stone-900">{graft.rootstock.name}</span>
                    </div>
                  ) : (
                    <div className="flex justify-between">
                      <span className="text-stone-500">Rootstock</span>
                      <span className="text-stone-400">Ungrafted</span>
                    </div>
                  )}
                  {graft && (
                    <div className="flex justify-between">
                      <span className="text-stone-500">Compatibility</span>
                      <span className="font-medium text-emerald-700">
                        {pct(graft.compatibility_score)}
                      </span>
                    </div>
                  )}
                </div>
              </div>
              <div className="rounded-2xl border border-stone-200 bg-white p-5">
                <p className="mb-3 text-[10px] sm:text-xs font-semibold uppercase tracking-wider text-stone-400">
                  Soil Environment
                </p>
                <div className="space-y-2 text-xs sm:text-sm">
                  {[
                    { label: "Profile", value: soil.name },
                    { label: "Type", value: soil.soil_type },
                    { label: "Climate", value: soil.climate_zone },
                    { label: "pH", value: soil.ph_level },
                    { label: "Salinity", value: `${soil.salinity_level} dS/m` },
                  ].map((r) => (
                    <div key={r.label} className="flex justify-between">
                      <span className="text-stone-500">{r.label}</span>
                      <span className="font-medium capitalize text-stone-900">{r.value}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {/* ── Risk Factors ────────────────────────────────────────── */}
            {results.risk_factors.length > 0 && (
              <div className="rounded-2xl border border-stone-200 bg-white p-6">
                <h2 className="mb-4 text-sm font-semibold text-stone-900">
                  Risk Factors
                </h2>
                <ul className="space-y-2.5">
                  {results.risk_factors.map((risk, i) => (
                    <li key={i} className="flex items-start gap-3">
                      <div className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-amber-100">
                        <svg
                          className="h-3 w-3 text-amber-600"
                          fill="none"
                          viewBox="0 0 24 24"
                          strokeWidth={2.5}
                          stroke="currentColor"
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z"
                          />
                        </svg>
                      </div>
                      <p className="text-sm text-stone-700">{risk}</p>
                    </li>
                  ))}
                </ul>
              </div>
            )}

            {/* ── NPK Adjustments ─────────────────────────────────────── */}
            {rec && (
              <div className="rounded-2xl border border-stone-200 bg-white p-6">
                <h2 className="mb-5 text-sm font-semibold text-stone-900">
                  Fertilisation — Applied vs Recommended
                </h2>
                <div className="grid gap-8 grid-cols-1 sm:grid-cols-3">
                  <NpkBar
                    label="Nitrogen (N)"
                    applied={scenario.applied_nitrogen}
                    recommended={typeof rec.nitrogen === "number" ? rec.nitrogen : 0}
                  />
                  <NpkBar
                    label="Phosphorus (P)"
                    applied={scenario.applied_phosphorus}
                    recommended={typeof rec.phosphorus === "number" ? rec.phosphorus : 0}
                  />
                  <NpkBar
                    label="Potassium (K)"
                    applied={scenario.applied_potassium}
                    recommended={typeof rec.potassium === "number" ? rec.potassium : 0}
                  />
                </div>
                {rec.irrigation_notes && (
                  <div className="mt-5 rounded-xl bg-stone-50 p-4">
                    <p className="text-xs font-semibold text-stone-500">Irrigation Notes</p>
                    <p className="mt-1 text-sm text-stone-700">{rec.irrigation_notes}</p>
                  </div>
                )}
                {rec.additional_notes && (
                  <div className="mt-3 rounded-xl bg-stone-50 p-4">
                    <p className="text-xs font-semibold text-stone-500">Additional Notes</p>
                    <p className="mt-1 text-sm text-stone-700">{rec.additional_notes}</p>
                  </div>
                )}
              </div>
            )}

            {/* ── Growth Timeline ──────────────────────────────────────── */}
            {results.growth_timeline.length > 0 && (
              <div className="rounded-2xl border border-stone-200 bg-white p-6">
                <h2 className="mb-5 text-sm font-semibold text-stone-900">
                  Week-by-Week Growth Timeline
                </h2>
                <GrowthChart timeline={results.growth_timeline} />

                {/* Timeline table */}
                <div className="mt-6 overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="border-b border-stone-100">
                        <th className="pb-2 pr-4 text-left text-xs font-semibold text-stone-400">Week</th>
                        <th className="pb-2 pr-4 text-left text-xs font-semibold text-stone-400">Stage</th>
                        <th className="pb-2 pr-4 text-right text-xs font-semibold text-stone-400">Height</th>
                        <th className="pb-2 text-left text-xs font-semibold text-stone-400">Notes</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-stone-50">
                      {results.growth_timeline.map((w) => (
                        <tr key={w.week} className="hover:bg-stone-50">
                          <td className="py-2 pr-4 text-xs font-medium text-stone-500">W{w.week}</td>
                          <td className="py-2 pr-4 text-xs capitalize text-stone-700">{w.stage}</td>
                          <td className="py-2 pr-4 text-right text-xs text-stone-700">{w.expected_height_cm} cm</td>
                          <td className="py-2 text-xs text-stone-400">{w.notes}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            )}

            {/* ── AI Analysis ──────────────────────────────────────────── */}
            {results.ai_analysis && (
              <div className="rounded-2xl border border-emerald-100 bg-emerald-50 p-6">
                <div className="mb-4 flex items-center gap-2">
                  <div className="flex h-8 w-8 items-center justify-center rounded-full bg-emerald-700">
                    <svg className="h-4 w-4 text-white" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" d="M9.813 15.904 9 18.75l-.813-2.846a4.5 4.5 0 0 0-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 0 0 3.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 0 0 3.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 0 0-3.09 3.09Z" />
                    </svg>
                  </div>
                  <h2 className="text-sm font-semibold text-emerald-900">AI Analysis</h2>
                </div>
                <div className="prose prose-sm max-w-none text-emerald-900">
                  {results.ai_analysis.split("\n\n").map((para, i) => (
                    <p key={i} className="mb-3 text-sm leading-relaxed last:mb-0">
                      {para}
                    </p>
                  ))}
                </div>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}
