"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, 
    Eye, 
    ChevronLeft, 
    ChevronRight,
    Users,
    ShieldAlert,
    UserCheck,
    Clock
} from "lucide-react"
import { usersApi, adminCompaniesApi, type ApiUser, type AdminCompany } from "@/lib/api"
import { getCurrentUser, isAdminUser } from "@/lib/auth"
import { toast } from "sonner"
import { Skeleton } from "@/components/ui/skeleton"
import { useTranslation } from "@/lib/i18n"
import { motion } from "framer-motion"

const userDateFormatter = new Intl.DateTimeFormat("pt-BR", {
    dateStyle: "medium",
})

export default function AdminUsersPage() {
    const router = useRouter()
    const { t } = useTranslation()
    const [users, setUsers] = useState<ApiUser[]>([])
    const [loading, setLoading] = useState(true)
    const [searchTerm, setSearchTerm] = useState("")
    const [page, setPage] = useState(1)
    const [totalUsers, setTotalUsers] = useState(0)

    const [isDialogOpen, setIsDialogOpen] = useState(false)
    const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
    const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)

    const [creating, setCreating] = useState(false)
    const [updating, setUpdating] = useState(false)
    const [deleting, setDeleting] = useState(false)
    const [viewing, setViewing] = useState(false)

    const [selectedUser, setSelectedUser] = useState<ApiUser | null>(null)
    const [companies, setCompanies] = useState<AdminCompany[]>([])
    const [currentUser, setCurrentUser] = useState<ApiUser | null>(null)

    const [formData, setFormData] = useState({
        name: "",
        email: "",
        password: "",
        role: "candidate",
        status: "active",
        companyId: "",
    })
    const [editFormData, setEditFormData] = useState({
        name: "",
        email: "",
        role: "",
        status: "",
        password: "",
    })

    useEffect(() => {
        const user = getCurrentUser()
        if (!isAdminUser(user)) {
            router.push("/dashboard")
            return
        }
        setCurrentUser(user as ApiUser)
        loadUsers()
        if (user?.role === 'superadmin') {
            loadCompanies()
        }
    }, [router])

    const loadCompanies = async () => {
        try {
            const data = await adminCompaniesApi.list(undefined, 1, 100)
            setCompanies(data.data || [])
        } catch (error) { }
    }

    const limit = 10
    const totalPages = Math.max(1, Math.ceil(totalUsers / limit))

    const loadUsers = async (targetPage = page) => {
        const pageNum = typeof targetPage === 'number' ? targetPage : page
        try {
            setLoading(true)
            const data = await usersApi.list({ page: pageNum, limit })
            setUsers(data?.data || [])
            setTotalUsers(data?.pagination?.total || 0)
            setPage(data?.pagination?.page || pageNum)
        } catch (error) {
            toast.error("Erro ao carregar usuários")
        } finally {
            setLoading(false)
        }
    }

    const handleCreate = async () => {
        try {
            setCreating(true)
            await usersApi.create({ ...formData, roles: [formData.role] })
            toast.success("Usuário criado com sucesso")
            setIsDialogOpen(false)
            setFormData({ name: "", email: "", password: "", role: "candidate", status: "active", companyId: "" })
            loadUsers(1)
        } catch (error: any) {
            toast.error(error.message || "Erro ao criar usuário")
        } finally {
            setCreating(false)
        }
    }

    const handleEdit = (user: ApiUser, isViewing = false) => {
        setSelectedUser(user)
        setEditFormData({
            name: user.name,
            email: user.email,
            role: user.role,
            status: user.status || "active",
            password: "",
        })
        setViewing(isViewing)
        setIsEditDialogOpen(true)
    }

    const handleUpdate = async () => {
        if (!selectedUser) return
        try {
            setUpdating(true)
            const payload: any = { ...editFormData, roles: [editFormData.role] }
            if (!payload.password) delete payload.password
            await usersApi.update(selectedUser.id, payload)
            toast.success("Usuário atualizado com sucesso")
            setIsEditDialogOpen(false)
            loadUsers()
        } catch (error) {
            toast.error("Erro ao atualizar usuário")
        } finally {
            setUpdating(false)
        }
    }

    const confirmDelete = async () => {
        if (!selectedUser) return
        try {
            setDeleting(true)
            await usersApi.delete(selectedUser.id)
            toast.success("Usuário excluído com sucesso")
            loadUsers(page)
            setIsDeleteDialogOpen(false)
        } catch (error) {
            toast.error("Erro ao excluir usuário")
        } finally {
            setDeleting(false)
        }
    }

    const getRoleBadge = (role: string) => {
        const variants: any = {
            superadmin: "destructive",
            admin: "default",
            recruiter: "secondary",
            candidate: "outline"
        }
        return <Badge variant={variants[role] || "outline"} className="capitalize">{role}</Badge>
    }

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

    return (
        <div className="container py-8 space-y-8">
            {/* Header */}
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                <motion.div initial={{ opacity: 0, x: -20 }} animate={{ opacity: 1, x: 0 }}>
                    <h1 className="text-4xl font-extrabold tracking-tight">Gerenciar Usuários</h1>
                    <p className="text-muted-foreground text-lg">Controle de acessos e permissões da plataforma</p>
                </motion.div>
                <div className="flex items-center gap-3">
                    <Button variant="outline" size="lg" onClick={() => loadUsers()} disabled={loading} className="shadow-sm">
                        <RefreshCw className={`h-4 w-4 mr-2 ${loading ? "animate-spin" : ""}`} />
                        Atualizar
                    </Button>
                    <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                        <DialogTrigger asChild>
                            <Button size="lg" className="gap-2 shadow-md hover:shadow-lg transition-all">
                                <Plus className="h-5 w-5" />
                                Novo Usuário
                            </Button>
                        </DialogTrigger>
                        <DialogContent className="max-w-md">
                            <DialogHeader>
                                <DialogTitle>Criar Novo Usuário</DialogTitle>
                                <DialogDescription>Preencha os dados para adicionar um novo membro.</DialogDescription>
                            </DialogHeader>
                            <div className="grid gap-4 py-4">
                                <div className="grid gap-2">
                                    <Label htmlFor="name">Nome Completo</Label>
                                    <Input id="name" value={formData.name} onChange={(e) => setFormData({ ...formData, name: e.target.value })} />
                                </div>
                                <div className="grid gap-2">
                                    <Label htmlFor="email">E-mail</Label>
                                    <Input id="email" type="email" value={formData.email} onChange={(e) => setFormData({ ...formData, email: e.target.value })} />
                                </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 })} />
                                </div>
                                <div className="grid grid-cols-2 gap-4">
                                    <div className="grid gap-2">
                                        <Label>Papel (Role)</Label>
                                        <Select value={formData.role} onValueChange={(v) => setFormData({ ...formData, role: v })}>
                                            <SelectTrigger><SelectValue /></SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="admin">Admin</SelectItem>
                                                <SelectItem value="recruiter">Recrutador</SelectItem>
                                                <SelectItem value="candidate">Candidato</SelectItem>
                                            </SelectContent>
                                        </Select>
                                    </div>
                                    <div className="grid gap-2">
                                        <Label>Status</Label>
                                        <Select value={formData.status} onValueChange={(v) => setFormData({ ...formData, status: v })}>
                                            <SelectTrigger><SelectValue /></SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="active">Ativo</SelectItem>
                                                <SelectItem value="inactive">Inativo</SelectItem>
                                            </SelectContent>
                                        </Select>
                                    </div>
                                </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-6 md:grid-cols-2 lg:grid-cols-4">
                <Card className="border-l-4 border-l-blue-500 shadow-sm">
                    <CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
                        <CardTitle className="text-sm font-medium">Total de Usuários</CardTitle>
                        <Users className="h-4 w-4 text-blue-500" />
                    </CardHeader>
                    <CardContent><div className="text-2xl font-bold">{totalUsers}</div></CardContent>
                </Card>
                <Card className="border-l-4 border-l-red-500 shadow-sm">
                    <CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
                        <CardTitle className="text-sm font-medium">Administradores</CardTitle>
                        <ShieldAlert className="h-4 w-4 text-red-500" />
                    </CardHeader>
                    <CardContent><div className="text-2xl font-bold">{users.filter(u => u.role === "admin" || u.role === "superadmin").length}</div></CardContent>
                </Card>
                <Card className="border-l-4 border-l-green-500 shadow-sm">
                    <CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
                        <CardTitle className="text-sm font-medium">Ativos agora</CardTitle>
                        <UserCheck className="h-4 w-4 text-green-500" />
                    </CardHeader>
                    <CardContent><div className="text-2xl font-bold">{users.filter(u => u.status === "active").length}</div></CardContent>
                </Card>
                <Card className="border-l-4 border-l-amber-500 shadow-sm">
                    <CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
                        <CardTitle className="text-sm font-medium">Novos (24h)</CardTitle>
                        <Clock className="h-4 w-4 text-amber-500" />
                    </CardHeader>
                    <CardContent><div className="text-2xl font-bold">--</div></CardContent>
                </Card>
            </div>

            {/* Main Content */}
            <Card className="border-0 shadow-xl overflow-hidden bg-card/50 backdrop-blur-sm">
                <CardHeader className="border-b bg-muted/30">
                    <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 e-mail..."
                                value={searchTerm}
                                onChange={(e) => setSearchTerm(e.target.value)}
                                className="pl-10 h-11 border-muted-foreground/20"
                            />
                        </div>
                    </div>
                </CardHeader>
                <CardContent className="p-0">
                    {loading ? (
                        <div className="p-8 space-y-4">
                            {[...Array(5)].map((_, i) => <Skeleton key={i} className="h-16 w-full rounded-lg" />)}
                        </div>
                    ) : (
                        <Table>
                            <TableHeader className="bg-muted/50">
                                <TableRow>
                                    <TableHead className="font-bold">Nome</TableHead>
                                    <TableHead className="font-bold">E-mail</TableHead>
                                    <TableHead className="font-bold">Papel</TableHead>
                                    <TableHead className="font-bold">Status</TableHead>
                                    <TableHead className="font-bold">Criado em</TableHead>
                                    <TableHead className="text-right font-bold">Ações</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {filteredUsers.length === 0 ? (
                                    <TableRow><TableCell colSpan={6} className="text-center py-20 text-muted-foreground">Nenhum usuário encontrado</TableCell></TableRow>
                                ) : (
                                    filteredUsers.map((user) => (
                                        <TableRow key={user.id} className="hover:bg-muted/30 transition-colors">
                                            <TableCell className="font-semibold">{user.name}</TableCell>
                                            <TableCell className="text-muted-foreground">{user.email}</TableCell>
                                            <TableCell>{getRoleBadge(user.role)}</TableCell>
                                            <TableCell>
                                                <Badge variant={user.status === "active" ? "default" : "secondary"}>
                                                    {user.status === "active" ? "Ativo" : "Inativo"}
                                                </Badge>
                                            </TableCell>
                                            <TableCell className="text-muted-foreground">
                                                {user.created_at || (user as any).createdAt ? userDateFormatter.format(new Date(user.created_at || (user as any).createdAt)) : "-"}
                                            </TableCell>
                                            <TableCell className="text-right">
                                                <div className="flex items-center justify-end gap-1">
                                                    <Button variant="ghost" size="icon" onClick={() => handleEdit(user, true)} className="hover:text-primary">
                                                        <Eye className="h-5 w-5" />
                                                    </Button>
                                                    <Button variant="ghost" size="icon" onClick={() => handleEdit(user)} className="hover:text-blue-600" disabled={user.role === "superadmin"}>
                                                        <Pencil className="h-5 w-5" />
                                                    </Button>
                                                    <Button variant="ghost" size="icon" className="hover:text-destructive hover:bg-destructive/10" onClick={() => { setSelectedUser(user); setIsDeleteDialogOpen(true); }} disabled={user.role === "superadmin"}>
                                                        <Trash2 className="h-5 w-5" />
                                                    </Button>
                                                </div>
                                            </TableCell>
                                        </TableRow>
                                    ))
                                )}
                            </TableBody>
                        </Table>
                    )}
                    
                    {!loading && totalPages > 1 && (
                        <div className="p-4 border-t bg-muted/10 flex items-center justify-between">
                            <p className="text-sm text-muted-foreground">
                                Página <span className="text-foreground font-medium">{page}</span> de <span className="text-foreground font-medium">{totalPages}</span>
                            </p>
                            <div className="flex gap-2">
                                <Button variant="outline" size="sm" onClick={() => loadUsers(page - 1)} disabled={page <= 1}>Anterior</Button>
                                <Button variant="outline" size="sm" onClick={() => loadUsers(page + 1)} disabled={page >= totalPages}>Próxima</Button>
                            </div>
                        </div>
                    )}
                </CardContent>
            </Card>

            {/* Edit / View Dialog */}
            <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
                <DialogContent className="max-w-md">
                    <DialogHeader>
                        <DialogTitle>{viewing ? "Detalhes do Usuário" : "Editar Usuário"}</DialogTitle>
                    </DialogHeader>
                    <div className="grid gap-4 py-4">
                        <div className="grid gap-2">
                            <Label>Nome</Label>
                            <Input value={editFormData.name} onChange={(e) => setEditFormData({ ...editFormData, name: e.target.value })} readOnly={viewing} />
                        </div>
                        <div className="grid gap-2">
                            <Label>E-mail</Label>
                            <Input value={editFormData.email} onChange={(e) => setEditFormData({ ...editFormData, email: e.target.value })} readOnly={viewing} />
                        </div>
                        {!viewing && (
                            <div className="grid gap-2">
                                <Label>Senha (Deixe em branco para não alterar)</Label>
                                <Input type="password" value={editFormData.password} onChange={(e) => setEditFormData({ ...editFormData, password: e.target.value })} />
                            </div>
                        )}
                        <div className="grid grid-cols-2 gap-4">
                            <div className="grid gap-2">
                                <Label>Papel</Label>
                                <Select value={editFormData.role} onValueChange={(v) => setEditFormData({ ...editFormData, role: v })} disabled={viewing}>
                                    <SelectTrigger><SelectValue /></SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="admin">Admin</SelectItem>
                                        <SelectItem value="recruiter">Recrutador</SelectItem>
                                        <SelectItem value="candidate">Candidato</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>
                            <div className="grid gap-2">
                                <Label>Status</Label>
                                <Select value={editFormData.status} onValueChange={(v) => setEditFormData({ ...editFormData, status: v })} disabled={viewing}>
                                    <SelectTrigger><SelectValue /></SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="active">Ativo</SelectItem>
                                        <SelectItem value="inactive">Inativo</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>
                        </div>
                    </div>
                    <DialogFooter>
                        <Button variant="outline" onClick={() => setIsEditDialogOpen(false)}>{viewing ? "Fechar" : "Cancelar"}</Button>
                        {!viewing && (
                            <Button onClick={handleUpdate} disabled={updating}>
                                {updating && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
                                Salvar Alterações
                            </Button>
                        )}
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            <ConfirmModal
                isOpen={isDeleteDialogOpen}
                onClose={() => setIsDeleteDialogOpen(false)}
                onConfirm={confirmDelete}
                title="Excluir Usuário"
                description={`Tem certeza que deseja excluir ${selectedUser?.name}?`}
            />
        </div>
    )
}
