import { notFound } from "next/navigation"

import FormShell from "@/components/app/FormShell"
import PageHeader from "@/components/app/PageHeader"
import PageShell from "@/components/app/PageShell"
import { Button } from "@/components/ui/button"
import UserForm from "@/features/users/components/UserForm"

import { getAllRoles } from "@/features/roles/service"
import { getUserById } from "@/features/users/service"
import type { Role } from "@/features/roles/types"

interface EditUserPageProps {
  params: Promise<{ id: string }>
}

export default async function EditUserPage({ params }: EditUserPageProps) {
  const { id } = await params
  const [user, roles] = await Promise.all([getUserById(id), getAllRoles()])

  if (!user) {
    notFound()
  }

  const availableRoles = roles.map((r: Role) => ({ id: r.id, name: r.name }))

  const initialData = {
    id: user.id,
    name: user.name,
    email: user.email,
    isActive: user.isActive,
    roleIds: user.roles.map((ur) => ur.roleId),
  }

  return (
    <PageShell>
      <PageHeader
        title="Edit User"
        actions={
          <Button asChild variant="secondary">
            <a href="/users">Back</a>
          </Button>
        }
      />
      <FormShell>
        <UserForm initialData={initialData} availableRoles={availableRoles} />
      </FormShell>
    </PageShell>
  )
}
