import Link from "next/link";
import { notFound } from "next/navigation";
import { getServerSession } from "next-auth";
import EmptyState from "@/components/EmptyState";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { getDepartmentLabel } from "@/lib/departments";
import { canManageHumanCapital } from "@/lib/human-capital";
import { locationOptions } from "@/lib/mock";
import { ROLE_LABELS } from "@/lib/utils";
import type { UserRole } from "@/lib/types";

function toUserRole(value: string | null | undefined): UserRole {
  if (value === "owner" || value === "leader" || value === "employee") {
    return value;
  }
  return "employee";
}

export default async function PersonDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const session = await getServerSession(authOptions);
  const { id } = await params;
  const user = await prisma.user.findUnique({
    where: { id },
    select: {
      id: true,
      name: true,
      email: true,
      department: true,
      departmentRole: true,
      userRoles: {
        include: { role: true },
        orderBy: { assignedAt: "asc" },
        take: 1,
      },
    },
  });

  if (!user) {
    notFound();
  }

  const resolvedRole = toUserRole(user.userRoles[0]?.role.key);
  const roleLabel = ROLE_LABELS[resolvedRole];
  const displayName = user.name?.trim() || user.email;
  const departmentLabel = user.department ? getDepartmentLabel(user.department) : "Sin departamento";
  const departmentRole = user.departmentRole ?? "Sin rol de departamento";
  const canViewLifecycle = canManageHumanCapital(session?.user.role, session?.user.department);

  const profile = canViewLifecycle
    ? await prisma.employeeProfile.findUnique({
        where: { userId: user.id },
      })
    : null;

  const lifecycleEvents = canViewLifecycle
    ? await prisma.employeeLifecycleEvent.findMany({
        where: { userId: user.id },
        orderBy: [{ effectiveAt: "desc" }, { createdAt: "desc" }],
        take: 60,
      })
    : [];
  const profileLocationName = profile?.locationId
    ? locationOptions.find((location) => location.id === profile.locationId)?.name ?? profile.locationId
    : "-";

  return (
    <div className="space-y-6">
      <Link href="/people" className="text-body font-semibold text-benell-brown hover:underline">
        ← Volver a Personas
      </Link>

      <header className="rounded-benell border border-benell-stroke bg-benell-surface p-6">
        <h1 className="text-display">{displayName}</h1>
        <p className="text-body-lg text-benell-text-soft">{roleLabel}</p>
        <p className="text-body mt-2 text-benell-text-soft text-tabular">
          {departmentLabel} · {departmentRole} · {user.email}
        </p>
      </header>

      {canViewLifecycle ? (
        <>
          <section className="rounded-benell border border-benell-stroke bg-benell-surface p-5">
            <h2 className="text-h2 font-semibold">Ficha de Capital Humano</h2>
            <div className="mt-3 grid grid-cols-1 gap-2 text-body text-benell-text-soft sm:grid-cols-2">
              <p>Estatus laboral: {profile?.employmentStatus ?? "sin perfil"}</p>
              <p>Tipo: {profile?.employmentType ?? "-"}</p>
              <p>FTE: {profile?.fte ?? "-"}</p>
              <p>Fecha de ingreso: {profile?.hireDate ? profile.hireDate.toISOString().slice(0, 10) : "-"}</p>
              <p>Manager ID: {profile?.managerUserId ?? "-"}</p>
              <p>Ubicación: {profileLocationName}</p>
            </div>
          </section>

          <section className="rounded-benell border border-benell-stroke bg-benell-surface p-5">
            <h2 className="text-h2 font-semibold">Timeline de lifecycle</h2>
            {lifecycleEvents.length === 0 ? (
              <p className="text-body mt-3 text-benell-text-soft">No hay eventos registrados.</p>
            ) : (
              <ul className="mt-3 space-y-2">
                {lifecycleEvents.map((event) => (
                  <li key={event.id} className="rounded-lg border border-benell-stroke bg-white px-3 py-2">
                    <p className="text-body font-semibold text-benell-text">{event.eventType}</p>
                    <p className="text-caption text-benell-text-soft">
                      {event.effectiveAt.toISOString().slice(0, 10)} · {event.reason ?? "sin motivo"}
                    </p>
                  </li>
                ))}
              </ul>
            )}
          </section>
        </>
      ) : (
        <EmptyState
          title="Vista de seguimiento individual"
          description="El detalle de lifecycle está visible solo para Owner y líderes de Capital Humano."
        />
      )}
    </div>
  );
}
