import Link from "next/link";
import { notFound } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { canEditHorse, canManageOriginatedRecord, getCurrentUser } from "@/lib/auth";
import type { User } from "@/generated/prisma/client";
import {
  forecastNextHeat,
  daysInHeat,
  BREEDING_METHOD_LABELS,
  BREEDING_OUTCOME_LABELS,
  BREEDING_OUTCOME_COLORS,
  FOALING_OUTCOME_LABELS,
  FOALING_OUTCOME_COLORS,
} from "@/lib/breeding";
import { computeCOI, coiRiskLabel } from "@/lib/coi";
import { forecastColorGenetics, forecastHealthGenetics, type LocusForecast } from "@/lib/geneticsForecast";
import { Field } from "@/components/Field";
import {
  addHeatCycle,
  updateHeatCycle,
  deleteHeatCycle,
  addProgesteroneTest,
  updateProgesteroneTest,
  deleteProgesteroneTest,
  addUltrasoundExam,
  updateUltrasoundExam,
  deleteUltrasoundExam,
  addBreedingEvent,
  updateBreedingEvent,
  deleteBreedingEvent,
  addFoalingRecord,
  updateFoalingRecord,
  deleteFoalingRecord,
  setBreedingEventTransferable,
} from "./actions";

function fmt(d: Date | null): string {
  return d ? new Date(d).toLocaleDateString() : "—";
}

function toDateInputValue(d: Date | null): string | undefined {
  if (!d) return undefined;
  const date = new Date(d);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

function displayName(h: { registeredName: string | null; barnName: string | null } | null | undefined) {
  if (!h) return null;
  return h.registeredName || h.barnName || "Unnamed Horse";
}

const inputCls =
  "w-full rounded-md border border-neutral-300 dark:border-neutral-700 bg-white dark:bg-neutral-900 px-2 py-1.5 text-sm text-neutral-900 dark:text-neutral-200 focus:border-neutral-500 focus:dark:border-neutral-400 focus:outline-none";

export default async function BreedingPage(props: PageProps<"/horses/[id]/breeding">) {
  const { id } = await props.params;

  const horse = await prisma.horse.findUnique({
    where: { id },
    include: {
      heatCycles: {
        orderBy: { startDate: "desc" },
        include: {
          progesteroneTests: { orderBy: { testDate: "asc" } },
          ultrasoundExams: { orderBy: { examDate: "asc" } },
        },
      },
      breedingEventsAsMare: {
        orderBy: { breedingDate: "desc" },
        include: { stallion: true, originator: { select: { id: true, name: true } } },
      },
      breedingEventsAsStallion: {
        orderBy: { breedingDate: "desc" },
        include: { mare: true, originator: { select: { id: true, name: true } } },
      },
      foalingRecords: { orderBy: { createdAt: "desc" }, include: { breedingEvent: { include: { stallion: true } }, foal: true } },
      foalsAsDam: true,
    },
  });

  if (!horse) notFound();

  const currentUser = await getCurrentUser();
  const canEdit = !!currentUser && canEditHorse(currentUser, horse);

  const name = displayName(horse) ?? "Unnamed Horse";
  const basePath = `/horses/${horse.id}/breeding`;

  const forecast = forecastNextHeat(horse.heatCycles.map((c) => ({ startDate: c.startDate })));

  const stallions =
    horse.sex === "MARE"
      ? await prisma.horse.findMany({ where: { sex: "STALLION" }, select: { id: true, registeredName: true, barnName: true } })
      : [];

  const mares =
    horse.sex === "STALLION"
      ? await prisma.horse.findMany({ where: { sex: "MARE" }, select: { id: true, registeredName: true, barnName: true } })
      : [];

  const sp = await props.searchParams;
  const checkId = typeof sp.checkId === "string" ? sp.checkId : undefined;
  const editParam = (key: string) => (typeof sp[key] === "string" ? sp[key] : null);
  const editHeatId = editParam("editHeat");
  const editProgId = editParam("editProg");
  const editUsId = editParam("editUs");
  const editEventId = editParam("editEvent");
  const editFoalingId = editParam("editFoaling");

  const pairedSireId = horse.sex === "MARE" ? checkId : horse.sex === "STALLION" ? horse.id : undefined;
  const pairedDamId = horse.sex === "MARE" ? horse.id : horse.sex === "STALLION" ? checkId : undefined;

  const coiPairing = checkId && pairedSireId && pairedDamId ? await computeCOI(pairedSireId, pairedDamId) : null;
  const coiRisk = coiPairing ? coiRiskLabel(coiPairing.coi) : null;
  const partnerOptions = horse.sex === "MARE" ? stallions : mares;
  const partnerLabel = horse.sex === "MARE" ? "Stallion" : "Mare";
  const checkedPartnerName = checkId ? displayName(partnerOptions.find((p) => p.id === checkId)) : null;

  const [colorForecast, healthForecast] =
    checkId && pairedSireId && pairedDamId
      ? await Promise.all([forecastColorGenetics(pairedSireId, pairedDamId), forecastHealthGenetics(pairedSireId, pairedDamId)])
      : [null, null];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold">{name} — Breeding</h1>
          <p className="text-sm text-neutral-700 dark:text-neutral-300">
            {horse.sex === "MARE" && "Heat cycles, progesterone tests, breeding events, and foaling records."}
            {horse.sex === "STALLION" && "Breeding book — matings with mares, by date and method."}
            {horse.sex === "GELDING" && "Geldings are not used for breeding."}
          </p>
        </div>
        <Link
          href={`/horses/${horse.id}`}
          className="rounded-md border border-neutral-300 dark:border-neutral-700 px-4 py-2 text-sm font-medium hover:bg-neutral-50 hover:dark:bg-neutral-950"
        >
          Back to Profile
        </Link>
      </div>

      {horse.sex === "GELDING" && (
        <div className="rounded-lg border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 p-6 text-sm text-neutral-700 dark:text-neutral-300">
          Nothing to show here for geldings.
        </div>
      )}

      {(horse.sex === "MARE" || horse.sex === "STALLION") && (
        <section className="space-y-4 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 p-6">
          <h2 className="text-base font-semibold">COI Calculator</h2>
          <p className="text-sm text-neutral-700 dark:text-neutral-300">
            Check the estimated inbreeding coefficient for a foal from this {horse.sex === "MARE" ? "mare" : "stallion"} before breeding.
          </p>
          <form method="GET" className="flex flex-wrap items-end gap-2">
            <Field label={partnerLabel} compact>
              <select name="checkId" defaultValue={checkId ?? ""} required className={`${inputCls} max-w-xs`}>
                <option value="" disabled>Select {partnerLabel.toLowerCase()}</option>
                {partnerOptions.map((p) => (
                  <option key={p.id} value={p.id}>{displayName(p)}</option>
                ))}
              </select>
            </Field>
            <button type="submit" className="rounded-md bg-neutral-900 dark:bg-neutral-100 dark:text-neutral-900 px-3 py-1.5 text-sm font-medium text-white hover:bg-neutral-800 dark:hover:bg-neutral-200">
              Calculate
            </button>
          </form>
          {coiPairing && coiRisk && (
            <div className={`rounded-lg border p-4 ${coiRisk.bg} ${coiRisk.border}`}>
              <p className={`text-sm font-semibold ${coiRisk.text}`}>
                {name} × {checkedPartnerName}: estimated COI {(coiPairing.coi * 100).toFixed(2)}% — {coiRisk.label}
              </p>
              {coiPairing.commonAncestors.length > 0 && (
                <details className="mt-2 text-sm">
                  <summary className="cursor-pointer text-neutral-700 dark:text-neutral-300">
                    Common ancestors ({coiPairing.commonAncestors.length})
                  </summary>
                  <ul className="mt-2 space-y-1">
                    {coiPairing.commonAncestors.map((a) => (
                      <li key={a.ancestorId} className="text-neutral-800 dark:text-neutral-300">
                        <Link href={`/horses/${a.ancestorId}`} className="hover:underline">{a.name}</Link>
                        <span className="text-neutral-600 dark:text-neutral-400"> — contributes {(a.contribution * 100).toFixed(2)}%</span>
                      </li>
                    ))}
                  </ul>
                </details>
              )}
            </div>
          )}
        </section>
      )}

      {(colorForecast || healthForecast) && (
        <section className="space-y-6 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 p-6">
          <div>
            <h2 className="text-base font-semibold">Genetics Forecast</h2>
            <p className="text-sm text-neutral-700 dark:text-neutral-300">
              Predicted genotype odds for a foal from {name} × {checkedPartnerName}, from each parent&apos;s recorded
              genetics. Shows genotype probabilities only (Punnett-square math), not a prediction of visual
              appearance — dominance/expression varies by locus.
            </p>
          </div>
          <div>
            <h3 className="mb-2 text-sm font-semibold text-neutral-900 dark:text-neutral-200">Color Genetics</h3>
            <div className="space-y-1.5">
              {colorForecast?.map((locus) => <LocusForecastRow key={locus.id} locus={locus} />)}
            </div>
          </div>
          <div>
            <h3 className="mb-2 text-sm font-semibold text-neutral-900 dark:text-neutral-200">Health Genetics</h3>
            <div className="space-y-1.5">
              {healthForecast?.map((locus) => <LocusForecastRow key={locus.id} locus={locus} />)}
            </div>
          </div>
        </section>
      )}

      {horse.sex === "MARE" && (
        <>
          <section className="space-y-4 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 p-6">
            <h2 className="text-base font-semibold">Heat Cycles</h2>
            {forecast.nextExpectedDate && (
              <p className="rounded-md bg-sky-50 dark:bg-sky-950 px-3 py-2 text-sm text-sky-800 dark:text-sky-300">
                Next heat forecast around <strong>{fmt(forecast.nextExpectedDate)}</strong> (average interval{" "}
                {forecast.avgIntervalDays} days, based on {horse.heatCycles.length} recorded cycles).
              </p>
            )}
            {canEdit && (
              <form action={addHeatCycle.bind(null, horse.id)} className="grid grid-cols-2 gap-2 sm:grid-cols-5">
                <Field label="Start Date" required compact>
                  <input type="date" name="startDate" required className={inputCls} />
                </Field>
                <Field label="End Date" compact>
                  <input type="date" name="endDate" className={inputCls} />
                </Field>
                <Field label="Notes" compact>
                  <input name="notes" className={`${inputCls} sm:col-span-2`} />
                </Field>
                <button type="submit" className="self-end rounded-md bg-neutral-900 dark:bg-neutral-100 dark:text-neutral-900 px-3 py-1.5 text-sm font-medium text-white hover:bg-neutral-800 dark:hover:bg-neutral-200">
                  Add Cycle
                </button>
              </form>
            )}

            {horse.heatCycles.length === 0 ? (
              <p className="text-sm text-neutral-700 dark:text-neutral-300">No heat cycles recorded.</p>
            ) : (
              <div className="space-y-4">
                {horse.heatCycles.map((cycle) => {
                  const days = daysInHeat(cycle.startDate, cycle.endDate);
                  return (
                  <div key={cycle.id} className="rounded-md border border-neutral-200 dark:border-neutral-700 p-3">
                    {canEdit && editHeatId === cycle.id ? (
                      <form action={updateHeatCycle.bind(null, horse.id, cycle.id)} className="grid grid-cols-2 gap-2 sm:grid-cols-5">
                        <input type="hidden" name="_redirectTo" value={basePath} />
                        <Field label="Start Date" required compact>
                          <input type="date" name="startDate" required defaultValue={toDateInputValue(cycle.startDate)} className={inputCls} />
                        </Field>
                        <Field label="End Date" compact>
                          <input type="date" name="endDate" defaultValue={toDateInputValue(cycle.endDate)} className={inputCls} />
                        </Field>
                        <Field label="Notes" compact>
                          <input name="notes" defaultValue={cycle.notes ?? ""} className={`${inputCls} sm:col-span-2`} />
                        </Field>
                        <div className="flex items-end gap-3">
                          <button type="submit" className="rounded-md bg-neutral-900 dark:bg-neutral-100 dark:text-neutral-900 px-3 py-1.5 text-sm font-medium text-white hover:bg-neutral-800 dark:hover:bg-neutral-200">
                            Save
                          </button>
                          <Link href={basePath} className="text-sm text-neutral-700 dark:text-neutral-300 hover:underline">Cancel</Link>
                        </div>
                      </form>
                    ) : (
                      <div className="flex items-center justify-between">
                        <p className="text-sm font-medium text-neutral-900 dark:text-neutral-200">
                          {fmt(cycle.startDate)} {cycle.endDate ? `– ${fmt(cycle.endDate)}` : ""}
                          {days != null && <span className="ml-2 font-normal text-neutral-700 dark:text-neutral-300">({days} day{days === 1 ? "" : "s"})</span>}
                          {cycle.notes ? <span className="ml-2 font-normal text-neutral-700 dark:text-neutral-300">{cycle.notes}</span> : null}
                        </p>
                        {canEdit && (
                          <div className="flex gap-3">
                            <Link href={`${basePath}?editHeat=${cycle.id}`} className="text-xs text-neutral-700 dark:text-neutral-300 hover:underline">Edit Cycle</Link>
                            <form action={deleteHeatCycle.bind(null, horse.id, cycle.id)}>
                              <button type="submit" className="text-xs text-red-700 dark:text-red-300 hover:underline">Delete Cycle</button>
                            </form>
                          </div>
                        )}
                      </div>
                    )}

                    <div className="mt-2 grid grid-cols-1 gap-4 pl-3 sm:grid-cols-2">
                      <div>
                        <h4 className="mb-1 text-xs font-semibold uppercase text-neutral-600 dark:text-neutral-400">Progesterone Tests</h4>
                        {canEdit && (
                          <form
                            action={addProgesteroneTest.bind(null, horse.id, cycle.id)}
                            className="mb-2 grid grid-cols-2 gap-2"
                          >
                            <Field label="Test Date" required compact>
                              <input type="date" name="testDate" required className={inputCls} />
                            </Field>
                            <Field label="ng/mL" required compact>
                              <input type="number" step="0.01" name="valueNgMl" required className={inputCls} />
                            </Field>
                            <Field label="Notes" compact>
                              <input name="notes" className={inputCls} />
                            </Field>
                            <button type="submit" className="self-end rounded-md border border-neutral-300 dark:border-neutral-700 px-3 py-1.5 text-xs font-medium hover:bg-neutral-50 hover:dark:bg-neutral-950">
                              Add Test
                            </button>
                          </form>
                        )}
                        {cycle.progesteroneTests.length === 0 ? (
                          <p className="text-xs text-neutral-700 dark:text-neutral-300">No progesterone tests logged.</p>
                        ) : (
                          <div className="overflow-x-auto">
                            <table className="w-full text-left text-xs">
                            <thead className="text-neutral-600 dark:text-neutral-400">
                              <tr>
                                <th className="py-1 pr-3 font-medium">Date</th>
                                <th className="py-1 pr-3 font-medium">ng/mL</th>
                                <th className="py-1 pr-3 font-medium">Notes</th>
                                <th className="py-1 font-medium"></th>
                              </tr>
                            </thead>
                            <tbody>
                              {cycle.progesteroneTests.map((t) =>
                                canEdit && editProgId === t.id ? (
                                  <tr key={t.id} className="border-t border-neutral-100 dark:border-neutral-800 bg-neutral-50 dark:bg-neutral-950">
                                    <td colSpan={4} className="py-2">
                                      <form action={updateProgesteroneTest.bind(null, horse.id, t.id)} className="grid grid-cols-2 gap-2">
                                        <input type="hidden" name="_redirectTo" value={basePath} />
                                        <Field label="Test Date" required compact>
                                          <input type="date" name="testDate" required defaultValue={toDateInputValue(t.testDate)} className={inputCls} />
                                        </Field>
                                        <Field label="ng/mL" required compact>
                                          <input type="number" step="0.01" name="valueNgMl" required defaultValue={t.valueNgMl} className={inputCls} />
                                        </Field>
                                        <Field label="Notes" compact>
                                          <input name="notes" defaultValue={t.notes ?? ""} className={inputCls} />
                                        </Field>
                                        <div className="flex items-end gap-3">
                                          <button type="submit" className="rounded-md border border-neutral-300 dark:border-neutral-700 px-3 py-1.5 text-xs font-medium hover:bg-neutral-50 hover:dark:bg-neutral-950">Save</button>
                                          <Link href={basePath} className="text-xs text-neutral-700 dark:text-neutral-300 hover:underline">Cancel</Link>
                                        </div>
                                      </form>
                                    </td>
                                  </tr>
                                ) : (
                                  <tr key={t.id} className="border-t border-neutral-100 dark:border-neutral-800">
                                    <td className="py-1 pr-3">{fmt(t.testDate)}</td>
                                    <td className="py-1 pr-3">{t.valueNgMl}</td>
                                    <td className="py-1 pr-3">{t.notes ?? "—"}</td>
                                    <td className="py-1 text-right">
                                      {canEdit && (
                                        <div className="flex justify-end gap-2">
                                          <Link href={`${basePath}?editProg=${t.id}`} className="text-neutral-700 dark:text-neutral-300 hover:underline">Edit</Link>
                                          <form action={deleteProgesteroneTest.bind(null, horse.id, t.id)}>
                                            <button type="submit" className="text-red-700 dark:text-red-300 hover:underline">Delete</button>
                                          </form>
                                        </div>
                                      )}
                                    </td>
                                  </tr>
                                )
                              )}
                            </tbody>
                            </table>
                          </div>
                        )}
                      </div>

                      <div>
                        <h4 className="mb-1 text-xs font-semibold uppercase text-neutral-600 dark:text-neutral-400">Ultrasound Exams</h4>
                        {canEdit && (
                          <form
                            action={addUltrasoundExam.bind(null, horse.id, cycle.id)}
                            className="mb-2 grid grid-cols-2 gap-2"
                          >
                            <Field label="Exam Date" required compact>
                              <input type="date" name="examDate" required className={inputCls} />
                            </Field>
                            <label className="flex items-center gap-1.5 self-end pb-2 text-xs text-neutral-700 dark:text-neutral-300">
                              <input type="checkbox" name="twinsPresent" /> Twins present
                            </label>
                            <Field label="Findings / Notes" compact>
                              <input name="notes" className={`${inputCls} col-span-2`} />
                            </Field>
                            <button type="submit" className="col-span-2 rounded-md border border-neutral-300 dark:border-neutral-700 px-3 py-1.5 text-xs font-medium hover:bg-neutral-50 hover:dark:bg-neutral-950">
                              Add Exam
                            </button>
                          </form>
                        )}
                        {cycle.ultrasoundExams.length === 0 ? (
                          <p className="text-xs text-neutral-700 dark:text-neutral-300">No ultrasound exams logged.</p>
                        ) : (
                          <div className="overflow-x-auto">
                            <table className="w-full text-left text-xs">
                            <thead className="text-neutral-600 dark:text-neutral-400">
                              <tr>
                                <th className="py-1 pr-3 font-medium">Date</th>
                                <th className="py-1 pr-3 font-medium">Twins</th>
                                <th className="py-1 pr-3 font-medium">Notes</th>
                                <th className="py-1 font-medium"></th>
                              </tr>
                            </thead>
                            <tbody>
                              {cycle.ultrasoundExams.map((u) =>
                                canEdit && editUsId === u.id ? (
                                  <tr key={u.id} className="border-t border-neutral-100 dark:border-neutral-800 bg-neutral-50 dark:bg-neutral-950">
                                    <td colSpan={4} className="py-2">
                                      <form action={updateUltrasoundExam.bind(null, horse.id, u.id)} className="grid grid-cols-2 gap-2">
                                        <input type="hidden" name="_redirectTo" value={basePath} />
                                        <Field label="Exam Date" required compact>
                                          <input type="date" name="examDate" required defaultValue={toDateInputValue(u.examDate)} className={inputCls} />
                                        </Field>
                                        <label className="flex items-center gap-1.5 self-end pb-2 text-xs text-neutral-700 dark:text-neutral-300">
                                          <input type="checkbox" name="twinsPresent" defaultChecked={u.twinsPresent} /> Twins present
                                        </label>
                                        <Field label="Findings / Notes" compact>
                                          <input name="notes" defaultValue={u.notes ?? ""} className={`${inputCls} col-span-2`} />
                                        </Field>
                                        <div className="col-span-2 flex items-center gap-3">
                                          <button type="submit" className="rounded-md border border-neutral-300 dark:border-neutral-700 px-3 py-1.5 text-xs font-medium hover:bg-neutral-50 hover:dark:bg-neutral-950">Save</button>
                                          <Link href={basePath} className="text-xs text-neutral-700 dark:text-neutral-300 hover:underline">Cancel</Link>
                                        </div>
                                      </form>
                                    </td>
                                  </tr>
                                ) : (
                                  <tr key={u.id} className="border-t border-neutral-100 dark:border-neutral-800">
                                    <td className="py-1 pr-3">{fmt(u.examDate)}</td>
                                    <td className="py-1 pr-3">
                                      {u.twinsPresent ? (
                                        <span className="rounded-full border border-amber-300 dark:border-amber-700 bg-amber-100 dark:bg-amber-900 px-2 py-0.5 text-[11px] font-medium text-amber-800 dark:text-amber-300">
                                          Twins
                                        </span>
                                      ) : (
                                        "No"
                                      )}
                                    </td>
                                    <td className="py-1 pr-3">{u.notes ?? "—"}</td>
                                    <td className="py-1 text-right">
                                      {canEdit && (
                                        <div className="flex justify-end gap-2">
                                          <Link href={`${basePath}?editUs=${u.id}`} className="text-neutral-700 dark:text-neutral-300 hover:underline">Edit</Link>
                                          <form action={deleteUltrasoundExam.bind(null, horse.id, u.id)}>
                                            <button type="submit" className="text-red-700 dark:text-red-300 hover:underline">Delete</button>
                                          </form>
                                        </div>
                                      )}
                                    </td>
                                  </tr>
                                )
                              )}
                            </tbody>
                            </table>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                  );
                })}
              </div>
            )}
          </section>

          <BreedingEventsSection
            title="Breeding Events"
            basePath={basePath}
            canEdit={canEdit}
            currentUser={currentUser}
            thisHorse={horse}
            events={horse.breedingEventsAsMare}
            editEventId={editEventId}
            addForm={
              <form action={addBreedingEvent} className="grid grid-cols-2 gap-2 sm:grid-cols-6">
                <input type="hidden" name="mareId" value={horse.id} />
                <Field label="Stallion" compact>
                  <select name="stallionId" className={inputCls}>
                    <option value="">— external / not in system —</option>
                    {stallions.map((s) => (
                      <option key={s.id} value={s.id}>{displayName(s)}</option>
                    ))}
                  </select>
                </Field>
                <Field label="Stallion Name (if external)" compact>
                  <input name="stallionOther" className={inputCls} />
                </Field>
                <Field label="Method" required compact>
                  <select name="method" required defaultValue="IN_HAND" className={inputCls}>
                    {Object.entries(BREEDING_METHOD_LABELS).map(([value, label]) => (
                      <option key={value} value={value}>{label}</option>
                    ))}
                  </select>
                </Field>
                <Field label="Breeding Date" required compact>
                  <input type="date" name="breedingDate" required className={inputCls} />
                </Field>
                <Field label="Outcome" compact>
                  <select name="outcome" defaultValue="PENDING" className={inputCls}>
                    {Object.entries(BREEDING_OUTCOME_LABELS).map(([value, label]) => (
                      <option key={value} value={value}>{label}</option>
                    ))}
                  </select>
                </Field>
                <Field label="Pregnancy Check Date" compact>
                  <input type="date" name="pregnancyCheckDate" className={inputCls} />
                </Field>
                <Field label="Notes" compact>
                  <input name="notes" className={`${inputCls} sm:col-span-2`} />
                </Field>
                <button type="submit" className="self-end rounded-md bg-neutral-900 dark:bg-neutral-100 dark:text-neutral-900 px-3 py-1.5 text-sm font-medium text-white hover:bg-neutral-800 dark:hover:bg-neutral-200">
                  Add
                </button>
              </form>
            }
            partnerColumnLabel="Stallion"
            partnerOf={(ev) => (ev.stallion ? { id: ev.stallion.id, name: displayName(ev.stallion) } : { id: null, name: ev.stallionOther })}
            counterpartOwnerId={(ev) => ev.stallion?.currentOwnerId}
          />

          <section className="space-y-4 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 p-6">
            <h2 className="text-base font-semibold">Foaling Records</h2>
            {canEdit && (
              <form action={addFoalingRecord.bind(null, horse.id)} className="grid grid-cols-2 gap-2 sm:grid-cols-6">
                <Field label="Breeding Event" compact>
                  <select name="breedingEventId" className={inputCls}>
                    <option value="">— none —</option>
                    {horse.breedingEventsAsMare.map((ev) => (
                      <option key={ev.id} value={ev.id}>
                        {fmt(ev.breedingDate)} × {ev.stallion ? displayName(ev.stallion) : ev.stallionOther ?? "Unknown"}
                      </option>
                    ))}
                  </select>
                </Field>
                <Field label="Due Date" compact>
                  <input type="date" name="dueDate" className={inputCls} />
                </Field>
                <Field label="Foaling Date" compact>
                  <input type="date" name="foalingDate" className={inputCls} />
                </Field>
                <Field label="Outcome" compact>
                  <select name="outcome" defaultValue="PENDING" className={inputCls}>
                    {Object.entries(FOALING_OUTCOME_LABELS).map(([value, label]) => (
                      <option key={value} value={value}>{label}</option>
                    ))}
                  </select>
                </Field>
                <Field label="Link Foal Profile" compact>
                  <select name="foalId" className={inputCls}>
                    <option value="">— link foal profile —</option>
                    {horse.foalsAsDam.map((f) => (
                      <option key={f.id} value={f.id}>{displayName(f)}</option>
                    ))}
                  </select>
                </Field>
                <Field label="Complications" compact>
                  <input name="complications" className={inputCls} />
                </Field>
                <Field label="Notes" compact>
                  <input name="notes" className={`${inputCls} sm:col-span-2`} />
                </Field>
                <button type="submit" className="self-end rounded-md bg-neutral-900 dark:bg-neutral-100 dark:text-neutral-900 px-3 py-1.5 text-sm font-medium text-white hover:bg-neutral-800 dark:hover:bg-neutral-200">
                  Add
                </button>
              </form>
            )}

            {horse.foalingRecords.length === 0 ? (
              <p className="text-sm text-neutral-700 dark:text-neutral-300">No foaling records.</p>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-left text-sm">
                <thead className="text-neutral-700 dark:text-neutral-300">
                  <tr>
                    <th className="py-1 pr-3 font-medium">Due</th>
                    <th className="py-1 pr-3 font-medium">Foaled</th>
                    <th className="py-1 pr-3 font-medium">Outcome</th>
                    <th className="py-1 pr-3 font-medium">Stallion</th>
                    <th className="py-1 pr-3 font-medium">Foal</th>
                    <th className="py-1 font-medium"></th>
                  </tr>
                </thead>
                <tbody>
                  {horse.foalingRecords.map((f) =>
                    canEdit && editFoalingId === f.id ? (
                      <tr key={f.id} className="border-t border-neutral-100 dark:border-neutral-800 bg-neutral-50 dark:bg-neutral-950">
                        <td colSpan={6} className="py-2">
                          <form action={updateFoalingRecord.bind(null, horse.id, f.id)} className="grid grid-cols-2 gap-2 sm:grid-cols-6">
                            <input type="hidden" name="_redirectTo" value={basePath} />
                            <Field label="Breeding Event" compact>
                              <select name="breedingEventId" defaultValue={f.breedingEventId ?? ""} className={inputCls}>
                                <option value="">— none —</option>
                                {horse.breedingEventsAsMare.map((ev) => (
                                  <option key={ev.id} value={ev.id}>
                                    {fmt(ev.breedingDate)} × {ev.stallion ? displayName(ev.stallion) : ev.stallionOther ?? "Unknown"}
                                  </option>
                                ))}
                              </select>
                            </Field>
                            <Field label="Due Date" compact>
                              <input type="date" name="dueDate" defaultValue={toDateInputValue(f.dueDate)} className={inputCls} />
                            </Field>
                            <Field label="Foaling Date" compact>
                              <input type="date" name="foalingDate" defaultValue={toDateInputValue(f.foalingDate)} className={inputCls} />
                            </Field>
                            <Field label="Outcome" compact>
                              <select name="outcome" defaultValue={f.outcome} className={inputCls}>
                                {Object.entries(FOALING_OUTCOME_LABELS).map(([value, label]) => (
                                  <option key={value} value={value}>{label}</option>
                                ))}
                              </select>
                            </Field>
                            <Field label="Link Foal Profile" compact>
                              <select name="foalId" defaultValue={f.foalId ?? ""} className={inputCls}>
                                <option value="">— link foal profile —</option>
                                {horse.foalsAsDam.map((foal) => (
                                  <option key={foal.id} value={foal.id}>{displayName(foal)}</option>
                                ))}
                              </select>
                            </Field>
                            <Field label="Complications" compact>
                              <input name="complications" defaultValue={f.complications ?? ""} className={inputCls} />
                            </Field>
                            <Field label="Notes" compact>
                              <input name="notes" defaultValue={f.notes ?? ""} className={`${inputCls} sm:col-span-2`} />
                            </Field>
                            <div className="flex items-end gap-3">
                              <button type="submit" className="rounded-md bg-neutral-900 dark:bg-neutral-100 dark:text-neutral-900 px-3 py-1.5 text-sm font-medium text-white hover:bg-neutral-800 dark:hover:bg-neutral-200">
                                Save
                              </button>
                              <Link href={basePath} className="text-sm text-neutral-700 dark:text-neutral-300 hover:underline">Cancel</Link>
                            </div>
                          </form>
                        </td>
                      </tr>
                    ) : (
                      (() => {
                        const c = FOALING_OUTCOME_COLORS[f.outcome];
                        return (
                          <tr key={f.id} className="border-t border-neutral-100 dark:border-neutral-800">
                            <td className="py-1.5 pr-3">{fmt(f.dueDate)}</td>
                            <td className="py-1.5 pr-3">{fmt(f.foalingDate)}</td>
                            <td className="py-1.5 pr-3">
                              <span className={`rounded-full border px-2 py-0.5 text-xs font-medium ${c.bg} ${c.border} ${c.text}`}>
                                {FOALING_OUTCOME_LABELS[f.outcome]}
                              </span>
                            </td>
                            <td className="py-1.5 pr-3">
                              {f.breedingEvent?.stallion ? displayName(f.breedingEvent.stallion) : f.breedingEvent?.stallionOther ?? "—"}
                            </td>
                            <td className="py-1.5 pr-3">
                              {f.foal ? (
                                <Link href={`/horses/${f.foal.id}`} className="hover:underline">{displayName(f.foal)}</Link>
                              ) : (
                                "—"
                              )}
                            </td>
                            <td className="py-1.5 text-right">
                              {canEdit && (
                                <div className="flex justify-end gap-3">
                                  <Link href={`${basePath}?editFoaling=${f.id}`} className="text-xs text-neutral-700 dark:text-neutral-300 hover:underline">Edit</Link>
                                  <form action={deleteFoalingRecord.bind(null, horse.id, f.id)}>
                                    <button type="submit" className="text-xs text-red-700 dark:text-red-300 hover:underline">Delete</button>
                                  </form>
                                </div>
                              )}
                            </td>
                          </tr>
                        );
                      })()
                    )
                  )}
                </tbody>
                </table>
              </div>
            )}
          </section>
        </>
      )}

      {horse.sex === "STALLION" && (
        <BreedingEventsSection
          title="Breeding Book"
          basePath={basePath}
          canEdit={canEdit}
          currentUser={currentUser}
          thisHorse={horse}
          events={horse.breedingEventsAsStallion}
          editEventId={editEventId}
          addForm={
            <form action={addBreedingEvent} className="grid grid-cols-2 gap-2 sm:grid-cols-6">
              <input type="hidden" name="stallionId" value={horse.id} />
              <Field label="Mare" required compact>
                <select name="mareId" required className={inputCls}>
                  <option value="" disabled>Select mare</option>
                  {mares.map((m) => (
                    <option key={m.id} value={m.id}>{displayName(m)}</option>
                  ))}
                </select>
              </Field>
              <Field label="Method" required compact>
                <select name="method" required defaultValue="IN_HAND" className={inputCls}>
                  {Object.entries(BREEDING_METHOD_LABELS).map(([value, label]) => (
                    <option key={value} value={value}>{label}</option>
                  ))}
                </select>
              </Field>
              <Field label="Breeding Date" required compact>
                <input type="date" name="breedingDate" required className={inputCls} />
              </Field>
              <Field label="Outcome" compact>
                <select name="outcome" defaultValue="PENDING" className={inputCls}>
                  {Object.entries(BREEDING_OUTCOME_LABELS).map(([value, label]) => (
                    <option key={value} value={value}>{label}</option>
                  ))}
                </select>
              </Field>
              <Field label="Pregnancy Check Date" compact>
                <input type="date" name="pregnancyCheckDate" className={inputCls} />
              </Field>
              <Field label="Notes" compact>
                <input name="notes" className={`${inputCls} sm:col-span-2`} />
              </Field>
              <button type="submit" className="self-end rounded-md bg-neutral-900 dark:bg-neutral-100 dark:text-neutral-900 px-3 py-1.5 text-sm font-medium text-white hover:bg-neutral-800 dark:hover:bg-neutral-200">
                Add
              </button>
            </form>
          }
          partnerColumnLabel="Mare"
          partnerOf={(ev) => ({ id: ev.mare.id, name: displayName(ev.mare) })}
          counterpartOwnerId={(ev) => ev.mare.currentOwnerId}
        />
      )}
    </div>
  );
}

type BreedingEventLike = {
  id: string;
  breedingDate: Date;
  method: string;
  outcome: string;
  pregnancyCheckDate: Date | null;
  originatorId: string | null;
  originator: { id: string; name: string } | null;
  transferWithHorse: boolean;
};

/** Shared table+edit-row for the mare-side and stallion-side breeding event lists - same shape, only the partner column (stallion vs mare) differs. */
function BreedingEventsSection<T extends BreedingEventLike>({
  title,
  basePath,
  canEdit,
  currentUser,
  thisHorse,
  events,
  editEventId,
  addForm,
  partnerColumnLabel,
  partnerOf,
  counterpartOwnerId,
}: {
  title: string;
  basePath: string;
  canEdit: boolean;
  currentUser: User | null;
  thisHorse: { currentOwnerId: string | null };
  events: T[];
  editEventId: string | null;
  addForm: React.ReactNode;
  partnerColumnLabel: string;
  partnerOf: (ev: T) => { id: string | null; name: string | null };
  counterpartOwnerId: (ev: T) => string | null | undefined;
}) {
  return (
    <section className="space-y-4 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 p-6">
      <h2 className="text-base font-semibold">{title}</h2>
      {canEdit && addForm}

      {events.length === 0 ? (
        <p className="text-sm text-neutral-700 dark:text-neutral-300">No breeding events recorded.</p>
      ) : (
        <div className="overflow-x-auto">
          <table className="w-full text-left text-sm">
          <thead className="text-neutral-700 dark:text-neutral-300">
            <tr>
              <th className="py-1 pr-3 font-medium">Date</th>
              <th className="py-1 pr-3 font-medium">{partnerColumnLabel}</th>
              <th className="py-1 pr-3 font-medium">Method</th>
              <th className="py-1 pr-3 font-medium">Outcome</th>
              <th className="py-1 pr-3 font-medium">Preg. Check</th>
              <th className="py-1 font-medium"></th>
            </tr>
          </thead>
          <tbody>
            {events.map((ev) => {
              const partner = partnerOf(ev);
              const canManage =
                !!currentUser &&
                canManageOriginatedRecord(currentUser, ev, [thisHorse, { currentOwnerId: counterpartOwnerId(ev) ?? null }]);
              const isOriginator = !!currentUser && (currentUser.role === "ADMIN" || ev.originatorId === currentUser.id);
              return canManage && editEventId === ev.id ? (
                <tr key={ev.id} className="border-t border-neutral-100 dark:border-neutral-800 bg-neutral-50 dark:bg-neutral-950">
                  <td colSpan={6} className="py-2">
                    <form action={updateBreedingEvent.bind(null, ev.id)} className="grid grid-cols-2 gap-2 sm:grid-cols-6">
                      <input type="hidden" name="_redirectTo" value={basePath} />
                      <p className="text-xs text-neutral-600 dark:text-neutral-400 sm:col-span-2">
                        {partnerColumnLabel}: <span className="font-medium text-neutral-900 dark:text-neutral-200">{partner.name}</span>
                        {" "}(not editable here — delete and re-add to change the paired horse)
                      </p>
                      <Field label="Method" required compact>
                        <select name="method" required defaultValue={ev.method} className={inputCls}>
                          {Object.entries(BREEDING_METHOD_LABELS).map(([value, label]) => (
                            <option key={value} value={value}>{label}</option>
                          ))}
                        </select>
                      </Field>
                      <Field label="Breeding Date" required compact>
                        <input type="date" name="breedingDate" required defaultValue={toDateInputValue(ev.breedingDate)} className={inputCls} />
                      </Field>
                      <Field label="Outcome" compact>
                        <select name="outcome" defaultValue={ev.outcome} className={inputCls}>
                          {Object.entries(BREEDING_OUTCOME_LABELS).map(([value, label]) => (
                            <option key={value} value={value}>{label}</option>
                          ))}
                        </select>
                      </Field>
                      <Field label="Pregnancy Check Date" compact>
                        <input type="date" name="pregnancyCheckDate" defaultValue={toDateInputValue(ev.pregnancyCheckDate)} className={inputCls} />
                      </Field>
                      {partner.id === null && (
                        <Field label="Stallion Name (if external)" compact>
                          <input name="stallionOther" defaultValue={partner.name ?? ""} className={inputCls} />
                        </Field>
                      )}
                      <div className="flex items-end gap-3">
                        <button type="submit" className="rounded-md bg-neutral-900 dark:bg-neutral-100 dark:text-neutral-900 px-3 py-1.5 text-sm font-medium text-white hover:bg-neutral-800 dark:hover:bg-neutral-200">
                          Save
                        </button>
                        <Link href={basePath} className="text-sm text-neutral-700 dark:text-neutral-300 hover:underline">Cancel</Link>
                      </div>
                    </form>
                  </td>
                </tr>
              ) : (
                <tr key={ev.id} className="border-t border-neutral-100 dark:border-neutral-800">
                  <td className="py-1.5 pr-3">{fmt(ev.breedingDate)}</td>
                  <td className="py-1.5 pr-3">
                    {partner.id ? (
                      <Link href={`/horses/${partner.id}`} className="hover:underline">{partner.name}</Link>
                    ) : (
                      partner.name ?? "—"
                    )}
                  </td>
                  <td className="py-1.5 pr-3">
                    {BREEDING_METHOD_LABELS[ev.method as keyof typeof BREEDING_METHOD_LABELS]}
                    {!isOriginator && ev.transferWithHorse && ev.originator && (
                      <span className="ml-1 text-[10px] text-neutral-500 dark:text-neutral-400">· via {ev.originator.name}</span>
                    )}
                  </td>
                  <td className="py-1.5 pr-3">
                    {(() => {
                      const c = BREEDING_OUTCOME_COLORS[ev.outcome as keyof typeof BREEDING_OUTCOME_COLORS];
                      return (
                        <span className={`rounded-full border px-2 py-0.5 text-xs font-medium ${c.bg} ${c.border} ${c.text}`}>
                          {BREEDING_OUTCOME_LABELS[ev.outcome as keyof typeof BREEDING_OUTCOME_LABELS]}
                        </span>
                      );
                    })()}
                  </td>
                  <td className="py-1.5 pr-3">{fmt(ev.pregnancyCheckDate)}</td>
                  <td className="py-1.5 text-right">
                    {(canManage || isOriginator) && (
                      <div className="flex justify-end gap-3">
                        {canManage && (
                          <>
                            <Link href={`${basePath}?editEvent=${ev.id}`} className="text-xs text-neutral-700 dark:text-neutral-300 hover:underline">Edit</Link>
                            <form action={deleteBreedingEvent.bind(null, ev.id)}>
                              <button type="submit" className="text-xs text-red-700 dark:text-red-300 hover:underline">Delete</button>
                            </form>
                          </>
                        )}
                        {isOriginator && (
                          <form action={setBreedingEventTransferable.bind(null, ev.id, !ev.transferWithHorse)}>
                            <button type="submit" className="text-xs text-neutral-500 dark:text-neutral-400 hover:underline">
                              {ev.transferWithHorse ? "Unshare" : "Share"}
                            </button>
                          </form>
                        )}
                      </div>
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
          </table>
        </div>
      )}
    </section>
  );
}

function LocusForecastRow({ locus }: { locus: LocusForecast }) {
  return (
    <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-1 rounded-md border border-neutral-100 dark:border-neutral-800 px-3 py-2 text-sm">
      <div>
        <span className="font-medium text-neutral-900 dark:text-neutral-200">{locus.name}</span>
        <span className="ml-1 text-neutral-500 dark:text-neutral-400">({locus.code})</span>
      </div>
      {locus.outcomes ? (
        <div className="flex flex-wrap justify-end gap-x-3 gap-y-1 text-neutral-800 dark:text-neutral-300">
          {locus.outcomes.map((o) => (
            <span key={o.genotype}>
              <strong>{Math.round(o.probability * 100)}%</strong> {o.genotype}
            </span>
          ))}
        </div>
      ) : (
        <span className="text-xs text-neutral-500 dark:text-neutral-400">
          {locus.sireGenotype || locus.damGenotype ? "One parent untested" : "Not tested"}
        </span>
      )}
    </div>
  );
}
