"use client"

import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Plus, Search, Trash2, Loader2, RefreshCw } from "lucide-react"
import { usersApi, type ApiUser } from "@/lib/api"
import { getCurrentUser } from "@/lib/auth"
import { toast } from "sonner"

export default function AdminUsersPage() {
    const router = useRouter()
    const [users, setUsers] = useState<ApiUser[]>([])
    const [loading, setLoading] = useState(true)
    const [searchTerm, setSearchTerm] = useState("")
    const [isDialogOpen, setIsDialogOpen] = useState(false)
    const [creating, setCreating] = useState(false)
    const [formData, setFormData] = useState({
        name: "",
        email: "",
        password: "",
        role: "jobSeeker",
    })

    useEffect(() => {
        const user = getCurrentUser()
        if (!user || (!user.roles?.includes("superadmin") && user.role !== "admin")) {
            router.push("/dashboard")
            return
        }
        loadUsers()
    }, [router])

    const loadUsers = async () => {
        try {
            setLoading(true)
            const data = await usersApi.list()
            setUsers(data || [])
        } catch (error) {
            console.error("Error loading users:", error)
            toast.error("Erro ao carregar usuários")
        } finally {
            setLoading(false)
        }
    }

    const handleCreate = async () => {
        try {
            setCreating(true)
            await usersApi.create(formData)
            toast.success("Usuário criado com sucesso!")
            setIsDialogOpen(false)
            setFormData({ name: "", email: "", password: "", role: "jobSeeker" })
            loadUsers()
        } catch (error) {
            console.error("Error creating user:", error)
            toast.error("Erro ao criar usuário")
        } finally {
            setCreating(false)
        }
    }

    const handleDelete = async (id: string) => {
        if (!confirm("Tem certeza que deseja excluir este usuário?")) return
        try {
            await usersApi.delete(id)
            toast.success("Usuário excluído!")
            loadUsers()
        } catch (error) {
            console.error("Error deleting user:", error)
            toast.error("Erro ao excluir usuário")
        }
    }

    const filteredUsers = users.filter(
        (user) =>
            user.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
            user.email?.toLowerCase().includes(searchTerm.toLowerCase())
    )

    const getRoleBadge = (role: string) => {
        const labels: Record<string, string> = {
            superadmin: "Super Admin",
            companyAdmin: "Admin Empresa",
            recruiter: "Recrutador",
            jobSeeker: "Candidato",
            admin: "Admin",
            company: "Empresa"
        }
        const colors: Record<string, "default" | "secondary" | "destructive" | "outline"> = {
            superadmin: "destructive",
            companyAdmin: "default",
            recruiter: "secondary",
            jobSeeker: "outline",
            admin: "destructive",
            company: "default"
        }
        const label = labels[role] || role || "Usuário"
        return <Badge variant={colors[role] || "outline"}>{label}</Badge>
    }

    return (
        <div className="space-y-8">
            {/* Header */}
            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-3xl font-bold text-foreground">Gestão de Usuários</h1>
                    <p className="text-muted-foreground mt-1">Gerencie todos os usuários da plataforma</p>
                </div>
                <div className="flex gap-2">
                    <Button variant="outline" onClick={loadUsers} disabled={loading}>
                        <RefreshCw className={`h-4 w-4 mr-2 ${loading ? "animate-spin" : ""}`} />
                        Atualizar
                    </Button>
                    <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                        <DialogTrigger asChild>
                            <Button className="gap-2">
                                <Plus className="h-4 w-4" />
                                Novo Usuário
                            </Button>
                        </DialogTrigger>
                        <DialogContent>
                            <DialogHeader>
                                <DialogTitle>Criar Novo Usuário</DialogTitle>
                                <DialogDescription>Preencha os dados do novo usuário</DialogDescription>
                            </DialogHeader>
                            <div className="grid gap-4 py-4">
                                <div className="grid gap-2">
                                    <Label htmlFor="name">Nome</Label>
                                    <Input
                                        id="name"
                                        value={formData.name}
                                        onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                                        placeholder="Nome completo"
                                    />
                                </div>
                                <div className="grid gap-2">
                                    <Label htmlFor="email">Email</Label>
                                    <Input
                                        id="email"
                                        type="email"
                                        value={formData.email}
                                        onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                                        placeholder="email@exemplo.com"
                                    />
                                </div>
                                <div className="grid gap-2">
                                    <Label htmlFor="password">Senha</Label>
                                    <Input
                                        id="password"
                                        type="password"
                                        value={formData.password}
                                        onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                                        placeholder="Senha segura"
                                    />
                                </div>
                                <div className="grid gap-2">
                                    <Label htmlFor="role">Função</Label>
                                    <Select value={formData.role} onValueChange={(v) => setFormData({ ...formData, role: v })}>
                                        <SelectTrigger>
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="superadmin">Super Admin</SelectItem>
                                            <SelectItem value="companyAdmin">Admin Empresa</SelectItem>
                                            <SelectItem value="recruiter">Recrutador</SelectItem>
                                            <SelectItem value="jobSeeker">Candidato</SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>
                            </div>
                            <DialogFooter>
                                <Button variant="outline" onClick={() => setIsDialogOpen(false)}>Cancelar</Button>
                                <Button onClick={handleCreate} disabled={creating}>
                                    {creating && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
                                    Criar Usuário
                                </Button>
                            </DialogFooter>
                        </DialogContent>
                    </Dialog>
                </div>
            </div>

            {/* Stats */}
            <div className="grid gap-4 md:grid-cols-4">
                <Card>
                    <CardHeader className="pb-3">
                        <CardDescription>Total de Usuários</CardDescription>
                        <CardTitle className="text-3xl">{users.length}</CardTitle>
                    </CardHeader>
                </Card>
                <Card>
                    <CardHeader className="pb-3">
                        <CardDescription>Admins</CardDescription>
                        <CardTitle className="text-3xl">
                            {users.filter((u) => u.role === "superadmin" || u.role === "companyAdmin").length}
                        </CardTitle>
                    </CardHeader>
                </Card>
                <Card>
                    <CardHeader className="pb-3">
                        <CardDescription>Recrutadores</CardDescription>
                        <CardTitle className="text-3xl">{users.filter((u) => u.role === "recruiter").length}</CardTitle>
                    </CardHeader>
                </Card>
                <Card>
                    <CardHeader className="pb-3">
                        <CardDescription>Candidatos</CardDescription>
                        <CardTitle className="text-3xl">{users.filter((u) => u.role === "jobSeeker").length}</CardTitle>
                    </CardHeader>
                </Card>
            </div>

            {/* Table */}
            <Card>
                <CardHeader>
                    <div className="flex items-center gap-4">
                        <div className="relative flex-1">
                            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                            <Input
                                placeholder="Buscar usuários por nome ou email..."
                                value={searchTerm}
                                onChange={(e) => setSearchTerm(e.target.value)}
                                className="pl-10"
                            />
                        </div>
                    </div>
                </CardHeader>
                <CardContent>
                    {loading ? (
                        <div className="flex items-center justify-center py-8">
                            <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
                        </div>
                    ) : (
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead>Nome</TableHead>
                                    <TableHead>Email</TableHead>
                                    <TableHead>Função</TableHead>
                                    <TableHead>Status</TableHead>
                                    <TableHead>Data Criação</TableHead>
                                    <TableHead className="text-right">Ações</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {filteredUsers.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={6} className="text-center text-muted-foreground py-8">
                                            Nenhum usuário encontrado
                                        </TableCell>
                                    </TableRow>
                                ) : (
                                    filteredUsers.map((user) => (
                                        <TableRow key={user.id}>
                                            <TableCell className="font-medium">{user.name}</TableCell>
                                            <TableCell>{user.email}</TableCell>
                                            <TableCell>{getRoleBadge(user.role)}</TableCell>
                                            <TableCell>
                                                <Badge variant={user.status === "active" ? "default" : "secondary"}>
                                                    {user.status === "active" ? "Ativo" : user.status}
                                                </Badge>
                                            </TableCell>
                                            <TableCell>
                                                {user.created_at ? new Date(user.created_at).toLocaleDateString("pt-BR") : "-"}
                                            </TableCell>
                                            <TableCell className="text-right">
                                                <Button
                                                    variant="ghost"
                                                    size="icon"
                                                    onClick={() => handleDelete(user.id)}
                                                    disabled={user.role === "superadmin"}
                                                >
                                                    <Trash2 className="h-4 w-4 text-destructive" />
                                                </Button>
                                            </TableCell>
                                        </TableRow>
                                    ))
                                )}
                            </TableBody>
                        </Table>
                    )}
                </CardContent>
            </Card>
        </div>
    )
}
