"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, Pencil } 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 [editingId, setEditingId] = useState<string | null>(null)
    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 () => {
        // This is now handled by handleSubmit
        handleSubmit()
    }

    const handleEditClick = (user: ApiUser) => {
        setEditingId(user.id)
        setFormData({
            name: user.name,
            email: user.email,
            password: "", // Password optional for update
            role: user.role,
        })
        setIsDialogOpen(true)
    }

    const handleSubmit = async () => {
        try {
            setCreating(true)
            if (editingId) {
                // Update existing user
                const updateData = { ...formData }
                if (!updateData.password) delete (updateData as any).password

                await usersApi.update(editingId, updateData)
                toast.success("Usuário atualizado com sucesso!")
            } else {
                // Create new user
                await usersApi.create(formData)
                toast.success("Usuário criado com sucesso!")
            }
            setIsDialogOpen(false)
            setFormData({ name: "", email: "", password: "", role: "jobSeeker" })
            setEditingId(null)
            loadUsers()
        } catch (error) {
            console.error("Error saving user:", error)
            toast.error("Erro ao salvar 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={(open) => {
                        setIsDialogOpen(open)
                        if (!open) {
                            setEditingId(null)
                            setFormData({ name: "", email: "", password: "", role: "jobSeeker" })
                        }
                    }}>
                        <DialogTrigger asChild>
                            <Button className="gap-2">
                                <Plus className="h-4 w-4" />
                                Novo Usuário
                            </Button>
                        </DialogTrigger>
                        <DialogContent>
                            <DialogHeader>
                                <DialogTitle>{editingId ? "Editar Usuário" : "Criar Novo Usuário"}</DialogTitle>
                                <DialogDescription>
                                    {editingId ? "Atualize os dados do usuário" : "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 {editingId && "(opcional)"}</Label>
                                    <Input
                                        id="password"
                                        type="password"
                                        value={formData.password}
                                        onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                                        placeholder={editingId ? "Deixe em branco para manter" : "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={handleSubmit} disabled={creating}>
                                    {creating && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
                                    {editingId ? "Salvar Alterações" : "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">
                                                <div className="flex justify-end gap-2">
                                                    <Button
                                                        variant="ghost"
                                                        size="icon"
                                                        onClick={() => handleEditClick(user)}
                                                    >
                                                        <Pencil className="h-4 w-4" />
                                                    </Button>
                                                    <Button
                                                        variant="ghost"
                                                        size="icon"
                                                        onClick={() => handleDelete(user.id)}
                                                        disabled={user.role === "superadmin"}
                                                    >
                                                        <Trash2 className="h-4 w-4 text-destructive" />
                                                    </Button>
                                                </div>
                                            </TableCell>
                                        </TableRow>
                                    ))
                                )}
                            </TableBody>
                        </Table>
                    )}
                </CardContent>
            </Card>
        </div>
    )
}
