import Link from "next/link";
import { Badge, EmptyState, Panel, SectionHeading } from "@/components/ui";
import { prisma } from "@/lib/prisma";

function isOnLeaveToday(start: Date | null, end: Date | null, today: Date) {
  if (!start || !end) {
    return false;
  }

  return today >= start && today <= end;
}

export default async function PeoplePage() {
  const people = await prisma.person.findMany({
    orderBy: { name: "asc" }
  });
  const today = new Date();

  return (
    <div className="space-y-3">
      <Panel className="p-2.5">
        <SectionHeading title="All people" count={people.length} />
        <div className="space-y-1">
          {people.length === 0 ? (
            <EmptyState text="No people added yet." />
          ) : (
            people.map((person) => {
              const onLeave = isOnLeaveToday(person.leaveStart, person.leaveEnd, today);

              const statusLabel = onLeave ? "on leave" : person.status;
              const statusClassName =
                person.status === "active" && !onLeave
                  ? "bg-stone-100 text-stone-500"
                  : onLeave
                    ? "bg-[var(--warning-soft)] text-amber-900"
                    : "bg-stone-200/80 text-stone-700";

              return (
                <Link key={person.id} href={`/people/${person.id}`} className="block rounded-xl border border-stone-200/70 bg-stone-50 px-3 py-2">
                  <div className="flex items-center justify-between gap-3">
                    <div className="min-w-0">
                      <p className="truncate text-sm font-medium text-stone-900">{person.name}</p>
                      <div className="mt-1 flex items-center gap-2">
                        <div className="flex flex-wrap gap-1.5">
                          {person.takesLunch ? <Badge>Lunch</Badge> : null}
                          {person.takesMandazi ? <Badge>Mandazi</Badge> : null}
                        </div>
                        <span className="text-stone-300">•</span>
                        <span
                          className={`inline-flex rounded-full px-2 py-0.5 text-[10px] font-medium capitalize ${statusClassName}`}
                        >
                          {statusLabel}
                        </span>
                      </div>
                    </div>
                    <svg viewBox="0 0 20 20" fill="none" aria-hidden="true" className="h-4 w-4 shrink-0 text-stone-400">
                      <path d="M7 4.5 12.5 10 7 15.5" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                  </div>
                </Link>
              );
            })
          )}
        </div>
      </Panel>
    </div>
  );
}
