import Link from "next/link";
import { notFound } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { SEX_LABELS, sexColors } from "@/lib/sex";
import { dueStatus } from "@/lib/health";
import { canEditHorse, getCurrentUser, hasPermission } from "@/lib/auth";
import { DeleteHorseButton } from "@/components/DeleteHorseButton";
import { Field } from "@/components/Field";
import { PhotoGallery } from "@/components/PhotoGallery";
import { addOwnershipRecord, assignOwner, deleteOwnershipRecord, updateOwnershipRecord, uploadPhoto } from "@/app/horses/actions";
import { requestTransfer } from "@/app/transfers/actions";
import { MAX_PHOTOS, MAX_PHOTO_BYTES, ALLOWED_PHOTO_MIME_TYPES, photoSrc, formatPhotoSize } from "@/lib/photos";
import { sanitizeRichText } from "@/lib/sanitize";
import { isBoringGenotype } from "@/lib/genetics";

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}`;
}

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";

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

const REGISTRY_LABELS: Record<string, string> = {
  UNREGISTERED: "Unregistered",
  APHC: "ApHC (Appaloosa Horse Club)",
  AQHA: "AQHA (American Quarter Horse Association)",
  APHA: "APHA (American Paint Horse Association)",
  JOCKEY_CLUB: "Jockey Club (Thoroughbred)",
  AMHA: "AMHA (American Miniature Horse Association)",
  AHA: "AHA (Arabian Horse Association)",
  ASHA: "ASHA (American Saddlebred Horse Association)",
  TWHBEA: "TWHBEA (Tennessee Walking Horse)",
  MFTHBA: "MFTHBA (Missouri Fox Trotting Horse)",
  RMHA: "RMHA (Rocky Mountain Horse Association)",
  OTHER: "Other",
};

export default async function HorseDetailPage(props: PageProps<"/horses/[id]">) {
  const { id } = await props.params;
  const sp = await props.searchParams;
  const editOwnershipId = typeof sp.editOwnership === "string" ? sp.editOwnership : null;

  const horse = await prisma.horse.findUnique({
    where: { id },
    include: {
      tags: true,
      photos: {
        select: { id: true, url: true, mimeType: true, sizeBytes: true, isPrimary: true, caption: true, createdAt: true },
        orderBy: { createdAt: "asc" },
      },
      sire: true,
      dam: true,
      foalsAsSire: true,
      foalsAsDam: true,
      colorGenetics: { include: { locus: true } },
      healthGenetics: { include: { test: true } },
      vaccinations: { select: { nextDueDate: true } },
      dewormings: { select: { nextDueDate: true } },
      ownershipHistory: { orderBy: { saleDate: "desc" } },
      currentOwner: true,
      bredBy: true,
    },
  });

  if (!horse) notFound();

  const currentUser = await getCurrentUser();
  const canEdit = !!currentUser && canEditHorse(currentUser, horse);
  const canManageHorses = !!currentUser && hasPermission(currentUser, "MANAGE_HORSES");
  const canTransfer = !!currentUser && !!horse.currentOwnerId && (horse.currentOwnerId === currentUser.id || currentUser.role === "ADMIN");

  const breeders =
    canManageHorses || canTransfer
      ? await prisma.user.findMany({
          where: { role: "BREEDER", isActive: true, id: { not: horse.currentOwnerId ?? undefined } },
          orderBy: { name: "asc" },
        })
      : [];

  const foals = [...horse.foalsAsSire, ...horse.foalsAsDam];

  // Homozygous-normal ("nn") results are the overwhelmingly common, uninteresting
  // case for most loci and are hidden here - see isBoringGenotype. Loci without a
  // "boring" default (Extension, Agouti, Dun) always show once tested.
  const notableColorGenetics = horse.colorGenetics.filter((cg) => !isBoringGenotype(cg.locus, cg.genotype));

  const dueDates = [...horse.vaccinations, ...horse.dewormings].map((r) => r.nextDueDate);
  const overdueCount = dueDates.filter((d) => dueStatus(d) === "overdue").length;
  const dueSoonCount = dueDates.filter((d) => dueStatus(d) === "due-soon").length;

  return (
    <div className="space-y-8">
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-semibold">{displayName(horse)}</h1>
          <p className="mt-1 flex items-center gap-2 text-sm text-neutral-700 dark:text-neutral-300">
            <span
              className={`rounded-full border px-2 py-0.5 text-xs font-medium ${sexColors(horse.sex).bg} ${sexColors(horse.sex).border} ${sexColors(horse.sex).text}`}
            >
              {SEX_LABELS[horse.sex] ?? horse.sex}
            </span>
            {horse.status.replace("_", " ")}
            {horse.breed ? ` · ${horse.breed}` : ""}
          </p>
          <p className="mt-1 text-sm text-neutral-700 dark:text-neutral-300">
            Born {fmt(horse.dateOfBirth)}
            {horse.status === "DECEASED" && horse.deceasedDate ? ` · Died ${fmt(horse.deceasedDate)}` : ""}
          </p>
          {horse.status === "FOR_SALE" && horse.salePrice != null && (
            <p className="mt-1 text-sm font-medium text-emerald-700 dark:text-emerald-300">Asking ${horse.salePrice.toLocaleString()}</p>
          )}
          {horse.sex === "STALLION" && horse.studFee != null && (
            <p className="mt-1 text-sm text-neutral-700 dark:text-neutral-300">Stud Fee: ${horse.studFee.toLocaleString()}</p>
          )}
          <p className="mt-1 text-sm text-neutral-700 dark:text-neutral-300">
            {horse.registry === "OTHER" ? horse.registryOther || "Other" : REGISTRY_LABELS[horse.registry]}
            {horse.registrationNumber ? ` · #${horse.registrationNumber}` : ""}
          </p>
          {horse.bredBy ? (
            <p className="mt-1 text-sm text-neutral-700 dark:text-neutral-300">
              Bred by{" "}
              <span className="font-medium text-neutral-900 dark:text-neutral-200">{horse.bredBy.farmName || horse.bredBy.name}</span>
              {horse.bredBy.website && (
                <>
                  {" · "}
                  <a href={horse.bredBy.website} target="_blank" rel="noopener noreferrer" className="text-neutral-700 dark:text-neutral-300 hover:underline">
                    {horse.bredBy.website.replace(/^https?:\/\//, "")}
                  </a>
                </>
              )}
              {(horse.bredBy.city || horse.bredBy.stateProvince || horse.bredBy.country) && (
                <span className="text-neutral-500 dark:text-neutral-400">
                  {" "}
                  ({[horse.bredBy.city, horse.bredBy.stateProvince, horse.bredBy.country].filter(Boolean).join(", ")})
                </span>
              )}
            </p>
          ) : (
            (horse.breederFarmName || horse.breederNames || horse.breederCity || horse.breederState || horse.breederCountry) && (
              <p className="mt-1 text-sm text-neutral-700 dark:text-neutral-300">
                Bred by {[horse.breederFarmName, horse.breederNames].filter(Boolean).join(" — ") || "Unknown"}
                {(horse.breederCity || horse.breederState || horse.breederCountry) && (
                  <span className="text-neutral-500 dark:text-neutral-400">
                    {" "}
                    ({[horse.breederCity, horse.breederState, horse.breederCountry].filter(Boolean).join(", ")})
                  </span>
                )}
              </p>
            )
          )}
          <p className="mt-1 text-sm text-neutral-700 dark:text-neutral-300">
            Owner:{" "}
            {horse.currentOwner ? (
              <span className="font-medium text-neutral-900 dark:text-neutral-200">
                {horse.currentOwner.id === currentUser?.id ? "You" : horse.currentOwner.name}
              </span>
            ) : (
              <span className="text-neutral-500 dark:text-neutral-400">Unassigned</span>
            )}
          </p>
        </div>
        <div className="flex gap-2">
          <Link
            href={`/horses/${horse.id}/health`}
            className="relative 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"
          >
            Health Records
            {overdueCount > 0 && (
              <span className="absolute -top-2 -right-2 rounded-full bg-red-600 px-1.5 py-0.5 text-[10px] font-semibold text-white">
                {overdueCount}
              </span>
            )}
            {overdueCount === 0 && dueSoonCount > 0 && (
              <span className="absolute -top-2 -right-2 rounded-full bg-amber-500 px-1.5 py-0.5 text-[10px] font-semibold text-white">
                {dueSoonCount}
              </span>
            )}
          </Link>
          {horse.sex !== "GELDING" && (
            <Link
              href={`/horses/${horse.id}/breeding`}
              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"
            >
              Breeding
            </Link>
          )}
          <Link
            href={`/horses/${horse.id}/pedigree`}
            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"
          >
            Pedigree
          </Link>
          {canEdit && (
            <Link
              href={`/horses/${horse.id}/edit`}
              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"
            >
              Edit
            </Link>
          )}
          {canManageHorses && <DeleteHorseButton horseId={horse.id} horseName={displayName(horse) ?? "this horse"} />}
        </div>
      </div>

      <div className="grid grid-cols-1 gap-6 md:grid-cols-3">
        <div className="space-y-6 md:col-span-1">
          <PhotoGallery
            horseId={horse.id}
            photos={horse.photos.map((photo) => ({ id: photo.id, src: photoSrc(horse.id, photo), isPrimary: photo.isPrimary }))}
            alt={displayName(horse) ?? ""}
            canEdit={canEdit}
          />

          {canEdit && (
            <div className="rounded-lg border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 p-3">
              {horse.photos.length < MAX_PHOTOS ? (
                <form action={uploadPhoto.bind(null, horse.id)} className="space-y-2">
                  <Field label={`Upload Photo (${horse.photos.length}/${MAX_PHOTOS}, max ${formatPhotoSize(MAX_PHOTO_BYTES)} each)`} compact>
                    <input
                      type="file"
                      name="photo"
                      accept={ALLOWED_PHOTO_MIME_TYPES.join(",")}
                      required
                      className="block w-full text-xs"
                    />
                  </Field>
                  <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">
                    Upload
                  </button>
                </form>
              ) : (
                <p className="text-xs text-neutral-600 dark:text-neutral-400">Maximum of {MAX_PHOTOS} photos reached.</p>
              )}
            </div>
          )}

          <div className="rounded-lg border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 p-4">
            <h2 className="mb-2 text-sm font-semibold text-neutral-900 dark:text-neutral-200">Foundation Percentage</h2>
            {horse.foundationPercentage != null ? (
              <p className="text-3xl font-semibold">
                {horse.foundationPercentage}%
                <span className="ml-2 text-xs font-normal text-neutral-600 dark:text-neutral-400">
                  {horse.foundationPercentageSource === "AUTO" ? "auto-calculated from sire/dam" : "manually set"}
                </span>
              </p>
            ) : (
              <p className="text-sm text-neutral-700 dark:text-neutral-300">Not set — add a sire and dam with known percentages, or set manually.</p>
            )}
          </div>

          <div className="rounded-lg border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 p-4">
            <h2 className="mb-2 text-sm font-semibold text-neutral-900 dark:text-neutral-200">Pedigree</h2>
            <dl className="space-y-1 text-sm">
              <div className="flex justify-between">
                <dt className="text-neutral-700 dark:text-neutral-300">Sire</dt>
                <dd>
                  {horse.sire ? (
                    <Link href={`/horses/${horse.sire.id}`} className="hover:underline">
                      {displayName(horse.sire)}
                    </Link>
                  ) : (
                    "—"
                  )}
                </dd>
              </div>
              <div className="flex justify-between">
                <dt className="text-neutral-700 dark:text-neutral-300">Dam</dt>
                <dd>
                  {horse.dam ? (
                    <Link href={`/horses/${horse.dam.id}`} className="hover:underline">
                      {displayName(horse.dam)}
                    </Link>
                  ) : (
                    "—"
                  )}
                </dd>
              </div>
            </dl>
            {foals.length > 0 && (
              <>
                <h3 className="mt-3 mb-1 text-xs font-semibold uppercase text-neutral-600 dark:text-neutral-400">Recorded Foals</h3>
                <ul className="space-y-1 text-sm">
                  {foals.map((foal) => (
                    <li key={foal.id}>
                      <Link href={`/horses/${foal.id}`} className="hover:underline">
                        {displayName(foal)}
                      </Link>
                    </li>
                  ))}
                </ul>
              </>
            )}
          </div>

          {horse.tags.length > 0 && (
            <div className="flex flex-wrap gap-1">
              {horse.tags.map((tag) => (
                <span key={tag.id} className="rounded-full bg-neutral-100 dark:bg-neutral-900 px-2 py-0.5 text-xs text-neutral-800 dark:text-neutral-300">
                  {tag.name}
                </span>
              ))}
            </div>
          )}

          {horse.notes && (
            <div className="rounded-lg border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 p-4">
              <h2 className="mb-2 text-sm font-semibold text-neutral-900 dark:text-neutral-200">Notes</h2>
              {/<[a-z][\s\S]*>/i.test(horse.notes) ? (
                <div className="rich-text text-sm text-neutral-800 dark:text-neutral-300" dangerouslySetInnerHTML={{ __html: sanitizeRichText(horse.notes) }} />
              ) : (
                <p className="whitespace-pre-wrap text-sm text-neutral-800 dark:text-neutral-300">{horse.notes}</p>
              )}
            </div>
          )}
        </div>

        <div className="space-y-6 md:col-span-2">
          <div className="rounded-lg border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 p-4">
            <h2 className="mb-3 text-sm font-semibold text-neutral-900 dark:text-neutral-200">Color Genetics</h2>
            {notableColorGenetics.length === 0 ? (
              <p className="text-sm text-neutral-700 dark:text-neutral-300">
                {horse.colorGenetics.length === 0
                  ? "No color genetics results recorded."
                  : "No notable results — clear (nn) loci are hidden."}
              </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-4 font-medium">Locus</th>
                    <th className="py-1 pr-4 font-medium">Genotype</th>
                    <th className="py-1 pr-4 font-medium">Test Date</th>
                    <th className="py-1 font-medium">Lab</th>
                  </tr>
                </thead>
                <tbody>
                  {notableColorGenetics.map((cg) => (
                    <tr key={cg.id} className="border-t border-neutral-100 dark:border-neutral-800">
                      <td className="py-1.5 pr-4">
                        {cg.locus.name} <span className="text-neutral-600 dark:text-neutral-400">({cg.locus.code})</span>
                      </td>
                      <td className="py-1.5 pr-4 font-mono">{cg.genotype}</td>
                      <td className="py-1.5 pr-4">{cg.testDate ? new Date(cg.testDate).toLocaleDateString() : "—"}</td>
                      <td className="py-1.5">{cg.lab ?? "—"}</td>
                    </tr>
                  ))}
                </tbody>
                </table>
              </div>
            )}
          </div>

          <div className="rounded-lg border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 p-4">
            <h2 className="mb-3 text-sm font-semibold text-neutral-900 dark:text-neutral-200">Health Genetics</h2>
            {horse.healthGenetics.length === 0 ? (
              <p className="text-sm text-neutral-700 dark:text-neutral-300">No health genetics results 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-4 font-medium">Test</th>
                    <th className="py-1 pr-4 font-medium">Result</th>
                    <th className="py-1 pr-4 font-medium">Test Date</th>
                    <th className="py-1 font-medium">Lab</th>
                  </tr>
                </thead>
                <tbody>
                  {horse.healthGenetics.map((hg) => (
                    <tr key={hg.id} className="border-t border-neutral-100 dark:border-neutral-800">
                      <td className="py-1.5 pr-4">
                        {hg.test.name} <span className="text-neutral-600 dark:text-neutral-400">({hg.test.code})</span>
                      </td>
                      <td className="py-1.5 pr-4 font-mono">{hg.result}</td>
                      <td className="py-1.5 pr-4">{hg.testDate ? new Date(hg.testDate).toLocaleDateString() : "—"}</td>
                      <td className="py-1.5">{hg.lab ?? "—"}</td>
                    </tr>
                  ))}
                </tbody>
                </table>
              </div>
            )}
          </div>
        </div>
      </div>

      {canManageHorses && !horse.currentOwnerId && (
        <section className="space-y-3 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 p-6">
          <h2 className="text-base font-semibold">Assign Owner</h2>
          <p className="text-sm text-neutral-700 dark:text-neutral-300">
            This horse has no registered owner yet. Assigning one makes them its owner starting from its date of
            birth and gives them edit access.
          </p>
          <form action={assignOwner.bind(null, horse.id)} className="flex flex-wrap items-end gap-2">
            <Field label="Breeder" compact>
              <select name="ownerId" required defaultValue="" className={`${inputCls} max-w-xs`}>
                <option value="" disabled>
                  Select breeder
                </option>
                {breeders.map((b) => (
                  <option key={b.id} value={b.id}>{b.name}</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">
              Assign
            </button>
          </form>
        </section>
      )}

      {canTransfer && (
        <section className="space-y-3 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 p-6">
          <h2 className="text-base font-semibold">Transfer This Horse</h2>
          <p className="text-sm text-neutral-700 dark:text-neutral-300">
            Sends a request to another breeder - ownership only moves once they accept it from their Transfers page.
            Double-check the email below before sending; it&apos;s a second confirmation that you&apos;ve picked the
            right person, since breeder names aren&apos;t unique.
          </p>
          <form action={requestTransfer.bind(null, horse.id)} className="flex flex-wrap items-end gap-2">
            <Field label="Transfer To" compact>
              <select name="toUserId" required defaultValue="" className={`${inputCls} max-w-sm`}>
                <option value="" disabled>
                  Select breeder
                </option>
                {breeders.map((b) => (
                  <option key={b.id} value={b.id}>
                    {b.name} — {b.email}
                    {b.farmName ? ` — ${b.farmName}` : ""}
                  </option>
                ))}
              </select>
            </Field>
            <Field label="Confirm Recipient's Email" compact>
              <input name="confirmEmail" type="email" required className={`${inputCls} max-w-xs`} />
            </Field>
            <Field label="Notes (optional)" compact>
              <input name="notes" className={`${inputCls} max-w-xs`} />
            </Field>
            <button type="submit" className="rounded-md border border-neutral-300 dark:border-neutral-700 px-3 py-1.5 text-sm font-medium hover:bg-neutral-50 hover:dark:bg-neutral-950">
              Send Transfer Request
            </button>
          </form>
        </section>
      )}

      <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">Ownership History</h2>
        {canManageHorses && (
          <form action={addOwnershipRecord.bind(null, horse.id)} className="grid grid-cols-2 gap-2 sm:grid-cols-7">
            <Field label="Owner Name" required compact>
              <input name="ownerName" required className={inputCls} />
            </Field>
            <Field label="Farm Name" compact>
              <input name="farmName" className={inputCls} />
            </Field>
            <Field label="Date of Sale" compact>
              <input type="date" name="saleDate" className={inputCls} />
            </Field>
            <Field label="City" compact>
              <input name="city" className={inputCls} />
            </Field>
            <Field label="State" compact>
              <input name="state" className={inputCls} />
            </Field>
            <Field label="Country" compact>
              <input name="country" 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 Owner
            </button>
          </form>
        )}
        {horse.ownershipHistory.length === 0 ? (
          <p className="text-sm text-neutral-700 dark:text-neutral-300">No ownership history 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">Owner</th>
                <th className="py-1 pr-3 font-medium">Farm</th>
                <th className="py-1 pr-3 font-medium">Date of Sale</th>
                <th className="py-1 pr-3 font-medium">Location</th>
                <th className="py-1 pr-3 font-medium">Notes</th>
                <th className="py-1 font-medium"></th>
              </tr>
            </thead>
            <tbody>
              {horse.ownershipHistory.map((o) =>
                canManageHorses && editOwnershipId === o.id ? (
                  <tr key={o.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={updateOwnershipRecord.bind(null, horse.id, o.id)} className="grid grid-cols-2 gap-2 sm:grid-cols-7">
                        <input type="hidden" name="_redirectTo" value={`/horses/${horse.id}`} />
                        <Field label="Owner Name" required compact>
                          <input name="ownerName" required defaultValue={o.ownerName} className={inputCls} />
                        </Field>
                        <Field label="Farm Name" compact>
                          <input name="farmName" defaultValue={o.farmName ?? ""} className={inputCls} />
                        </Field>
                        <Field label="Date of Sale" compact>
                          <input type="date" name="saleDate" defaultValue={toDateInputValue(o.saleDate)} className={inputCls} />
                        </Field>
                        <Field label="City" compact>
                          <input name="city" defaultValue={o.city ?? ""} className={inputCls} />
                        </Field>
                        <Field label="State" compact>
                          <input name="state" defaultValue={o.state ?? ""} className={inputCls} />
                        </Field>
                        <Field label="Country" compact>
                          <input name="country" defaultValue={o.country ?? ""} className={inputCls} />
                        </Field>
                        <Field label="Notes" compact>
                          <input name="notes" defaultValue={o.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={`/horses/${horse.id}`} className="text-sm text-neutral-700 dark:text-neutral-300 hover:underline">
                            Cancel
                          </Link>
                        </div>
                      </form>
                    </td>
                  </tr>
                ) : (
                  <tr key={o.id} className="border-t border-neutral-100 dark:border-neutral-800">
                    <td className="py-1.5 pr-3">{o.ownerName}</td>
                    <td className="py-1.5 pr-3">{o.farmName ?? "—"}</td>
                    <td className="py-1.5 pr-3">{fmt(o.saleDate)}</td>
                    <td className="py-1.5 pr-3">{[o.city, o.state, o.country].filter(Boolean).join(", ") || "—"}</td>
                    <td className="py-1.5 pr-3">{o.notes ?? "—"}</td>
                    <td className="py-1.5 text-right">
                      {canManageHorses && (
                        <div className="flex justify-end gap-3">
                          <Link href={`/horses/${horse.id}?editOwnership=${o.id}`} className="text-xs text-neutral-700 dark:text-neutral-300 hover:underline">
                            Edit
                          </Link>
                          <form action={deleteOwnershipRecord.bind(null, horse.id, o.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>
    </div>
  );
}
