import { prisma } from "@/lib/prisma";
import { requirePermissionOrBreeder } from "@/lib/auth";
import { FoalFlowBoard, type FoalFlowItem } from "@/components/FoalFlowBoard";
import { addToFoalFlow } from "./actions";
import { SEX_LABELS } from "@/lib/sex";

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 FoalsPage() {
  const user = await requirePermissionOrBreeder("MANAGE_FOAL_FLOW");
  const horseWhere = user.role === "ADMIN" ? {} : { currentOwnerId: user.id };
  const [inFlow, notInFlow] = await Promise.all([
    prisma.horse.findMany({ where: { ...horseWhere, foalFlowStage: { not: null } } }),
    prisma.horse.findMany({
      where: { ...horseWhere, foalFlowStage: null },
      select: { id: true, registeredName: true, barnName: true },
      orderBy: { createdAt: "desc" },
    }),
  ]);

  const items: FoalFlowItem[] = inFlow.map((h) => ({
    id: h.id,
    name: h.registeredName || h.barnName || "Unnamed Horse",
    sex: SEX_LABELS[h.sex] ?? h.sex,
    stage: h.foalFlowStage as string,
  }));

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-semibold">Foal Flow</h1>
        <p className="text-sm text-neutral-700 dark:text-neutral-300">Drag a card to move a foal through the workflow, from birth to sale.</p>
      </div>

      <section className="space-y-3 rounded-lg border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 p-4">
        <h2 className="text-sm font-semibold text-neutral-900 dark:text-neutral-200">Add a Horse to the Flow</h2>
        <form action={addToFoalFlow} className="flex flex-wrap gap-2">
          <select name="horseId" required className={`${inputCls} max-w-xs`}>
            <option value="" disabled>Select horse</option>
            {notInFlow.map((h) => (
              <option key={h.id} value={h.id}>{h.registeredName || h.barnName || "Unnamed Horse"}</option>
            ))}
          </select>
          <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">
            Add
          </button>
        </form>
      </section>

      <FoalFlowBoard initialItems={items} />
    </div>
  );
}
