import { notFound } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { requireUser } from "@/lib/auth";
import { HorseForm, type HorseFormInitialValues } from "@/components/HorseForm";
import { updateHorse } from "@/app/horses/actions";

function toDateInputValue(d: Date | null): string | undefined {
  if (!d) return undefined;
  // Build from local date parts (not toISOString, which is UTC and can shift
  // the date back a day) so the value matches what was originally typed in.
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

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

  const [horse, horses, loci, healthTests, breeders] = await Promise.all([
    prisma.horse.findUnique({
      where: { id },
      include: {
        tags: true,
        colorGenetics: true,
        healthGenetics: true,
      },
    }),
    prisma.horse.findMany({ select: { id: true, barnName: true, registeredName: true, sex: true } }),
    prisma.locus.findMany({ orderBy: { category: "asc" } }),
    prisma.healthTest.findMany({ orderBy: { name: "asc" } }),
    user.role === "ADMIN"
      ? prisma.user.findMany({ where: { role: "BREEDER" }, orderBy: { name: "asc" } })
      : Promise.resolve([]),
  ]);

  if (!horse) notFound();

  const breederOptions =
    user.role === "ADMIN" ? breeders.map((b) => ({ id: b.id, label: `${b.name} (${b.email})` })) : undefined;

  const horseOptions = horses.map((h) => ({
    id: h.id,
    label: h.registeredName || h.barnName || "Unnamed Horse",
    sex: h.sex,
  }));

  const initial: HorseFormInitialValues = {
    barnName: horse.barnName ?? undefined,
    registeredName: horse.registeredName ?? undefined,
    sex: horse.sex,
    breed: horse.breed ?? undefined,
    color: horse.color ?? undefined,
    dateOfBirth: toDateInputValue(horse.dateOfBirth),
    status: horse.status,
    deceasedDate: toDateInputValue(horse.deceasedDate),
    salePrice: horse.salePrice,
    studFee: horse.studFee,
    sireId: horse.sireId ?? undefined,
    damId: horse.damId ?? undefined,
    tags: horse.tags.map((t) => t.name).join(", "),
    notes: horse.notes ?? undefined,
    foundationPercentage: horse.foundationPercentage,
    foundationPercentageSource: horse.foundationPercentageSource,
    registry: horse.registry,
    registryOther: horse.registryOther ?? undefined,
    registrationNumber: horse.registrationNumber ?? undefined,
    microchipNumber: horse.microchipNumber ?? undefined,
    microchipDate: toDateInputValue(horse.microchipDate),
    microchipIssuer: horse.microchipIssuer ?? undefined,
    brandLocation: horse.brandLocation ?? undefined,
    brandImageUrl: horse.brandImageUrl ?? undefined,
    brandDescription: horse.brandDescription ?? undefined,
    breederFarmName: horse.breederFarmName ?? undefined,
    breederNames: horse.breederNames ?? undefined,
    breederCity: horse.breederCity ?? undefined,
    breederState: horse.breederState ?? undefined,
    breederCountry: horse.breederCountry ?? undefined,
    bredByUserId: horse.bredByUserId ?? undefined,
  };

  const colorGenetics = Object.fromEntries(
    horse.colorGenetics.map((cg) => [
      cg.locusId,
      { genotype: cg.genotype, testDate: toDateInputValue(cg.testDate), lab: cg.lab ?? undefined },
    ])
  );
  const healthGenetics = Object.fromEntries(
    horse.healthGenetics.map((hg) => [
      hg.testId,
      { result: hg.result, testDate: toDateInputValue(hg.testDate), lab: hg.lab ?? undefined },
    ])
  );

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-semibold">Edit {horse.registeredName || horse.barnName || "Horse"}</h1>
      <HorseForm
        action={updateHorse.bind(null, horse.id)}
        horses={horseOptions}
        loci={loci}
        healthTests={healthTests}
        initial={initial}
        colorGenetics={colorGenetics}
        healthGenetics={healthGenetics}
        breederOptions={breederOptions}
        currentHorseId={horse.id}
        submitLabel="Save Changes"
      />
    </div>
  );
}
