import Link from "next/link";
import { redirect } from "next/navigation";

import { ShellPage } from "@/components/page-templates";
import { SectionCard } from "@/components/ui";
import { getSession } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export default async function UserDetailPage({ params }: { params: Promise<{ userId: string }> }) {
  const { userId } = await params;
  const session = await getSession();
  if (!session) {
    redirect("/login");
  }

  const user = await prisma.user.findFirst({
    where: { id: userId, tenantId: session.tenantId },
    include: { role: true, assignedConversations: true }
  });

  if (!user) {
    redirect("/team?error=user_not_found");
  }

  return (
    <ShellPage
      shell="admin"
      title="User Detail"
      description="Role, status, assigned conversations, dan snapshot performa."
      actions={<Link href={`/team/${user.id}/edit`}>Edit user</Link>}
    >
      <div className="grid gap-6 xl:grid-cols-2">
        <SectionCard title="User profile">
          <p className="text-sm text-on-surface-variant">
            <strong>Nama:</strong> {user.fullName}
          </p>
          <p className="text-sm text-on-surface-variant">
            <strong>Email:</strong> {user.email}
          </p>
          <p className="text-sm text-on-surface-variant">
            <strong>Role:</strong> {user.role.name}
          </p>
          <p className="text-sm text-on-surface-variant">
            <strong>Status:</strong> {user.status}
          </p>
          <p className="text-sm text-on-surface-variant">
            <strong>Last login:</strong> {user.lastLoginAt?.toLocaleString() || "-"}
          </p>
        </SectionCard>
        <SectionCard title="Performance snapshot">
          <p className="text-sm text-on-surface-variant">Handled conversations: {user.assignedConversations.length}</p>
          <p className="text-sm text-on-surface-variant">Avg response time: -</p>
          <p className="text-sm text-on-surface-variant">Resolved count: -</p>
        </SectionCard>
      </div>
    </ShellPage>
  );
}
