import Link from "next/link";
import { notFound } from "next/navigation";
import { adjustPersonMandaziQtyAction, setPersonLeaveDateAction, setPersonModeAction, togglePersonMealAction } from "@/app/actions";
import { PersonDetailControls } from "@/components/person-detail-controls";
import { Badge, Panel, SectionHeading } from "@/components/ui";
import { prisma } from "@/lib/prisma";

export default async function PersonDetailPage({
  params
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const person = await prisma.person.findUnique({
    where: { id: Number(id) },
    include: {
      payments: {
        orderBy: { createdAt: "desc" }
      }
    }
  });

  if (!person) {
    notFound();
  }

  const currentMode =
    person.status === "paused" ? "paused" : person.leaveStart || person.leaveEnd ? "on_leave" : "active";

  return (
    <div className="space-y-3">
      <header className="space-y-2 pt-2">
        <Link href="/people" className="inline-flex text-sm text-[var(--muted)]">
          ← Back
        </Link>
        <h1 className="text-3xl font-semibold">{person.name}</h1>
      </header>

      <Panel>
        <SectionHeading title="Overview" />
        <div className="flex flex-wrap gap-2">
          {person.takesLunch ? <Badge>Lunch</Badge> : null}
          {person.takesMandazi ? <Badge>Mandazi</Badge> : null}
        </div>
      </Panel>

      <Panel>
        <SectionHeading title="Controls" />
        <PersonDetailControls
          person={{
            id: person.id,
            takesLunch: person.takesLunch,
            takesMandazi: person.takesMandazi,
            defaultMandaziQty: person.defaultMandaziQty,
            leaveStart: person.leaveStart,
            leaveEnd: person.leaveEnd,
            currentMode
          }}
          setPersonModeAction={setPersonModeAction}
          togglePersonMealAction={togglePersonMealAction}
          adjustPersonMandaziQtyAction={adjustPersonMandaziQtyAction}
          setPersonLeaveDateAction={setPersonLeaveDateAction}
        />
      </Panel>

      <Panel>
        <SectionHeading title="Payments" />
        <div className="space-y-2">
          {person.payments.map((payment) => (
            <div key={payment.id} className="rounded-xl bg-stone-50 px-3 py-2">
              <p className="text-sm font-medium">
                {payment.mealType.charAt(0).toUpperCase() + payment.mealType.slice(1)} • {payment.remainingDays} days remaining
              </p>
            </div>
          ))}
          {person.payments.length === 0 ? <p className="text-xs text-[var(--muted)]">No payments yet.</p> : null}
        </div>
      </Panel>
    </div>
  );
}
