import { notFound } from "next/navigation";
import { Pool } from "pg";
import { RoleForm } from "@/components/admin/roles/role-form";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";

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

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

async function getRole(id: string) {
  const result = await pool.query(
    `SELECT id, name, description, permissions, is_system, created_at, updated_at
     FROM "role" WHERE id = $1`,
    [id]
  );
  return result.rows[0] || null;
}

export default async function EditRolePage({ params }: PageProps) {
  const { id } = await params;
  const role = await getRole(id);

  if (!role) {
    notFound();
  }

  return (
    <div className="container mx-auto py-8 px-4 max-w-3xl">
      <Card>
        <CardHeader>
          <div className="flex items-center gap-2">
            <CardTitle>Edit Role: {role.name}</CardTitle>
            {role.is_system && <Badge variant="outline">System</Badge>}
          </div>
          <CardDescription>
            {role.is_system
              ? "System roles cannot be renamed or deleted, but permissions can be modified"
              : "Update role name, description, and permissions"}
          </CardDescription>
        </CardHeader>
        <CardContent>
          <RoleForm role={role} />
        </CardContent>
      </Card>
    </div>
  );
}
