import { notFound } from "next/navigation";
import { Pool } from "pg";
import { getSession } from "@/lib/auth-utils";
import { UserForm } from "@/components/admin/users/user-form";
import { UserSessions } from "@/components/admin/users/user-sessions";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { RoleBadge } from "@/components/admin/users/role-badge";
import { Badge } from "@/components/ui/badge";

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
});

interface PageProps {
  params: Promise<{ id: string }>;
}

async function getUser(id: string) {
  const result = await pool.query(
    `SELECT id, name, email, email_verified, image, role, banned, 
            banned_reason, ban_expires, requires_setup, created_at, updated_at
     FROM "user" WHERE id = $1`,
    [id]
  );
  return result.rows[0] || null;
}

async function getUserSessions(userId: string) {
  const result = await pool.query(
    `SELECT id, ip_address, user_agent, created_at, expires_at
     FROM "session" WHERE user_id = $1 ORDER BY created_at DESC`,
    [userId]
  );
  return result.rows;
}

export default async function UserDetailPage({ params }: PageProps) {
  const { id } = await params;
  const session = await getSession();
  const user = await getUser(id);

  if (!user) {
    notFound();
  }

  const sessions = await getUserSessions(id);
  const isCurrentUser = session?.user?.id === id;

  return (
    <div className="container mx-auto py-8 px-4">
      <div className="mb-8">
        <div className="flex items-center gap-4">
          <h1 className="text-3xl font-bold">{user.name}</h1>
          <RoleBadge role={user.role} />
          {user.banned && <Badge variant="destructive">Banned</Badge>}
          {isCurrentUser && <Badge variant="outline">You</Badge>}
        </div>
        <p className="text-muted-foreground mt-2">{user.email}</p>
      </div>

      <Tabs defaultValue="details" className="space-y-6">
        <TabsList>
          <TabsTrigger value="details">Details</TabsTrigger>
          <TabsTrigger value="sessions">Sessions ({sessions.length})</TabsTrigger>
        </TabsList>

        <TabsContent value="details">
          <Card>
            <CardHeader>
              <CardTitle>User Details</CardTitle>
              <CardDescription>
                Update user information and role
              </CardDescription>
            </CardHeader>
            <CardContent>
              <UserForm user={user} isCurrentUser={isCurrentUser} />
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="sessions">
          <Card>
            <CardHeader>
              <CardTitle>Active Sessions</CardTitle>
              <CardDescription>
                View and manage user&apos;s active sessions
              </CardDescription>
            </CardHeader>
            <CardContent>
              <UserSessions sessions={sessions} userId={id} />
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
