"use client"

import { useEffect, useState } from "react"
import { useParams, useRouter } from "next/navigation"
import Link from "next/link"
import { Save } from "lucide-react"

import { rolesApi } from "@/lib/api/roles"
import { usersApi } from "@/lib/api/users"
import { errorMessage } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import { Role } from "@/types/rbac"
import { ManagedUser } from "@/types/users"

import { Badge } from "@/components/ui/badge"
import { Button, buttonVariants } from "@/components/ui/button"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Skeleton } from "@/components/ui/skeleton"
import { toast } from "@/components/ui/toast"

export default function UserDetailPage() {
  const params = useParams<{ id: string }>()
  const router = useRouter()
  const userId = Number(params.id)

  const [user, setUser] = useState<ManagedUser | null>(null)
  const [roles, setRoles] = useState<Role[]>([])
  const [loadError, setLoadError] = useState<string | null>(null)
  const [roleId, setRoleId] = useState<string>("")
  const [saving, setSaving] = useState(false)

  function load() {
    setLoadError(null)
    Promise.all([usersApi.get(userId), rolesApi.list({ pageSize: 200, status: "Active" })])
      .then(([u, roleList]) => {
        setUser(u)
        setRoles(roleList.items)
        setRoleId(u.roleId ? String(u.roleId) : "")
      })
      .catch((err) => setLoadError(errorMessage(err)))
  }

  useEffect(() => {
    if (Number.isFinite(userId)) load()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [userId])

  async function handleSave() {
    if (!roleId) return
    setSaving(true)
    try {
      const result = await usersApi.updateRole(userId, { roleId: Number(roleId) })
      setUser(result)
      toast.success("Role updated", `${result.username} is now assigned to ${result.roleName}.`)
    } catch (err) {
      toast.error("Could not update role", errorMessage(err))
    } finally {
      setSaving(false)
    }
  }

  if (loadError && !user) {
    return (
      <div className="flex flex-col gap-4">
        <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-5 text-base text-destructive">{loadError}</div>
        <Link href="/dashboard/settings/users" className={cn(buttonVariants({ variant: "outline" }))}>
          Back to users
        </Link>
      </div>
    )
  }

  if (!user) {
    return (
      <div className="flex flex-col gap-3">
        <Skeleton className="h-10 w-72" />
        <Skeleton className="h-48 w-full" />
      </div>
    )
  }

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center gap-3">
        <div>
          <div className="flex items-center gap-3">
            <h1 className="text-2xl font-bold text-foreground">{user.username}</h1>
            <Badge
              variant="outline"
              className={cn(
                "h-6 w-fit justify-center border-transparent px-2.5 text-sm",
                user.status === "Active" ? "bg-success/10 text-success" : "bg-muted text-muted-foreground"
              )}
            >
              {user.status}
            </Badge>
          </div>
          <p className="text-base text-muted-foreground">{user.displayName}</p>
        </div>
      </div>

      <div className="flex flex-col gap-2 sm:max-w-sm">
        <Label className="text-base">Role</Label>
        <Select value={roleId || undefined} onValueChange={(v) => setRoleId(v ?? "")}>
          <SelectTrigger>
            <SelectValue placeholder="Select a role" />
          </SelectTrigger>
          <SelectContent>
            {roles.map((r) => (
              <SelectItem key={r.roleId} value={String(r.roleId)}>
                {r.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      <div className="flex justify-end gap-3">
        <Button variant="outline" size="lg" onClick={() => router.push("/dashboard/settings/users")}>
          Cancel
        </Button>
        <Button size="lg" onClick={handleSave} disabled={saving || !roleId}>
          <Save className="size-5" />
          {saving ? "Saving…" : "Save role"}
        </Button>
      </div>
    </div>
  )
}
