import AcceptInvitationForm from "@/components/AcceptInvitationForm";
import { hashInvitationToken } from "@/lib/invitations";
import { prisma } from "@/lib/prisma";
import { getDepartmentLabel } from "@/lib/departments";
import { ROLE_LABELS } from "@/lib/utils";

export default async function AcceptInvitationPage({
  searchParams,
}: {
  searchParams?: { token?: string; email?: string };
}) {
  const tokenFromUrl = searchParams?.token?.trim() ?? "";
  const emailFromUrl = searchParams?.email?.trim() ?? "";

  if (!tokenFromUrl || !emailFromUrl) {
    return (
      <main className="mx-auto max-w-xl p-6">
        <h1 className="text-display">Invitacion invalida</h1>
        <p className="text-body mt-2">Faltan parametros en el enlace de invitacion.</p>
      </main>
    );
  }

  const invitation = await prisma.invitation.findFirst({
    where: {
      email: emailFromUrl.toLowerCase(),
      tokenHash: hashInvitationToken(tokenFromUrl),
      acceptedAt: null,
      expiresAt: { gt: new Date() },
    },
    select: {
      inviteeName: true,
      department: true,
      departmentRole: true,
      roleKey: true,
    },
  });

  if (!invitation) {
    return (
      <main className="mx-auto max-w-xl p-6">
        <h1 className="text-display">Invitacion expirada</h1>
        <p className="text-body mt-2">Este enlace no es valido o ya fue utilizado.</p>
      </main>
    );
  }

  return (
    <main className="mx-auto max-w-xl p-6">
      <h1 className="text-display">Aceptar invitacion</h1>
      <p className="text-body mt-2">Completa tus datos para activar tu cuenta de Casa Benell.</p>
      <AcceptInvitationForm
        token={tokenFromUrl}
        email={emailFromUrl}
        defaultName={invitation.inviteeName}
        departmentLabel={getDepartmentLabel(invitation.department)}
        departmentRole={invitation.departmentRole}
        platformRoleLabel={ROLE_LABELS[invitation.roleKey]}
      />
    </main>
  );
}
