"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 } 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"

const userDateFormatter = new Intl.DateTimeFormat("en-US", {
    dateStyle: "medium",
    timeZone: "UTC",
})

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)

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

    // Action States
    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)

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

    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) {
            console.error("Error loading companies:", error)
        }
    }

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

    const loadUsers = async (targetPage = page) => {
        console.log(`[USER_FLOW] Loading users page: ${targetPage}`)
        try {
            setLoading(true)
            const data = await usersApi.list({ page: targetPage, limit })
            console.log("[USER_FLOW] Users loaded:", data)
            setUsers(data?.data || [])
            setTotalUsers(data?.pagination?.total || 0)
            setPage(data?.pagination?.page || targetPage)
        } catch (error) {
            console.error("[USER_FLOW] Error loading users:", error)
            toast.error(t('admin.users.messages.load_error'))
        } finally {
            setLoading(false)
        }
    }

    const handleCreate = async () => {
        console.log("[USER_FLOW] Creating user with data:", formData)
        try {
            setCreating(true)
            const payload = {
                ...formData,
                roles: [formData.role],
            }
            await usersApi.create(payload)
            toast.success(t('admin.users.messages.create_success'))
            setIsDialogOpen(false)
            setFormData({ name: "", email: "", password: "", role: "candidate", status: "active", companyId: "" })
            setPage(1)
            loadUsers(1)
        } catch (error) {
            console.error("[USER_FLOW] Error creating user:", error)
            toast.error(t('admin.users.messages.create_error'))
        } finally {
            setCreating(false)
        }
    }

    const handleView = (user: ApiUser) => {
        console.log("[USER_FLOW] Viewing user:", user)
        setSelectedUser(user)
        setEditFormData({
            name: user.name,
            email: user.email,
            role: user.role,
            status: user.status || "active",
        })
        setViewing(true)
        setIsEditDialogOpen(true)
    }

    const handleEdit = (user: ApiUser) => {
        console.log("[USER_FLOW] Editing user:", user)
        setSelectedUser(user)
        setEditFormData({
            name: user.name,
            email: user.email,
            role: user.role,
            status: user.status || "active",
        })
        setViewing(false)
        setIsEditDialogOpen(true)
    }

    const handleUpdate = async () => {
        if (!selectedUser) return
        console.log("[USER_FLOW] Updating user:", selectedUser.id, "with data:", editFormData)
        try {
            setUpdating(true)
            const payload = {
                ...editFormData,
                roles: [editFormData.role],
            }
            await usersApi.update(selectedUser.id, payload)
            toast.success(t('admin.users.messages.update_success'))
            setIsEditDialogOpen(false)
            loadUsers()
        } catch (error) {
            console.error("[USER_FLOW] Error updating user:", error)
            toast.error(t('admin.users.messages.update_error'))
        } finally {
            setUpdating(false)
        }
    }

    const handleDeleteClick = (user: ApiUser) => {
        console.log("[USER_FLOW] Delete click for user:", user)
        setSelectedUser(user)
        setIsDeleteDialogOpen(true)
    }

    const confirmDelete = async () => {
        if (!selectedUser) return
        console.log("[USER_FLOW] Confirming delete for user:", selectedUser.id)

        try {
            setDeleting(true)
            await usersApi.delete(selectedUser.id)
            toast.success(t('admin.users.messages.delete_success'))

            // UI Update logic
            if (users.length === 1 && page > 1) {
                setPage(page - 1)
                loadUsers(page - 1)
            } else {
                loadUsers(page)
            }
            setIsDeleteDialogOpen(false)
            setSelectedUser(null)
        } catch (error: any) {
            console.error("[USER_FLOW] Error deleting user:", error)
            // Error handling matching user request to see logs
            if (error.message && error.message.includes("403")) {
                toast.error("You don't have permission to delete this user (403)")
            } else {
                toast.error(t('admin.users.messages.delete_error'))
            }
        } finally {
            setDeleting(false)
        }
    }

    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",
            admin: "Company Admin",
            recruiter: "Recruiter",
            candidate: "Candidate",
            company: "Company"
        }
        const colors: Record<string, "default" | "secondary" | "destructive" | "outline"> = {
            superadmin: "destructive",
            admin: "default",
            recruiter: "secondary",
            candidate: "outline",
            company: "default"
        }
        const label = labels[role] || role || "User"
        return <Badge variant={colors[role] || "outline"}>{label}</Badge>
    }

    return (
        <div className="space-y-6 sm:space-y-8">
            {/* Header */}
            <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                <div>
                    <h1 className="text-2xl sm:text-3xl font-bold text-foreground">{t('admin.users.title')}</h1>
                    <p className="text-sm sm:text-base text-muted-foreground mt-1">{t('admin.users.subtitle')}</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" : ""}`} />
                        {t('admin.users.refresh')}
                    </Button>
                    <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                        <DialogTrigger asChild>
                            <Button className="gap-2">
                                <Plus className="h-4 w-4" />
                                {t('admin.users.new_user')}
                            </Button>
                        </DialogTrigger>
                        <DialogContent>
                            <DialogHeader>
                                <DialogTitle>{t('admin.users.create_dialog.title')}</DialogTitle>
                                <DialogDescription>{t('admin.users.create_dialog.description')}</DialogDescription>
                            </DialogHeader>
                            <div className="grid gap-4 py-4">
                                <div className="grid gap-2">
                                    <Label htmlFor="name">{t('admin.users.table.name')}</Label>
                                    <Input
                                        id="name"
                                        value={formData.name}
                                        onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                                        placeholder={t('admin.users.table.name')}
                                    />
                                </div>
                                <div className="grid gap-2">
                                    <Label htmlFor="email">{t('admin.users.table.email')}</Label>
                                    <Input
                                        id="email"
                                        type="email"
                                        value={formData.email}
                                        onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                                        placeholder={t('admin.users.table.email')}
                                    />
                                </div>
                                <div className="grid gap-2">
                                    <Input
                                        id="password"
                                        type="password"
                                        value={formData.password}
                                        onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                                        placeholder="Secure password"
                                    />
                                </div>
                                {currentUser?.role === 'superadmin' && (
                                    <div className="grid gap-2">
                                        <Label htmlFor="company">Company</Label>
                                        <Select value={formData.companyId} onValueChange={(v) => setFormData({ ...formData, companyId: v })}>
                                            <SelectTrigger>
                                                <SelectValue placeholder="Select a company" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                {companies.map((company) => (
                                                    <SelectItem key={company.id} value={company.id}>
                                                        {company.name}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                    </div>
                                )}
                                <div className="grid gap-2">
                                    <Label htmlFor="status">{t('admin.users.table.status')}</Label>
                                    <Select value={formData.status} onValueChange={(v) => setFormData({ ...formData, status: v })}>
                                        <SelectTrigger>
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="active">Active</SelectItem>
                                            <SelectItem value="inactive">Inactive</SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>
                                <div className="grid gap-2">
                                    <Label htmlFor="role">{t('admin.users.table.role')}</Label>
                                    <Select value={formData.role} onValueChange={(v) => setFormData({ ...formData, role: v })}>
                                        <SelectTrigger>
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="superadmin">Super Admin</SelectItem>
                                            <SelectItem value="admin">Company admin</SelectItem>
                                            <SelectItem value="recruiter">Recruiter</SelectItem>
                                            <SelectItem value="candidate">Candidate</SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>
                            </div>
                            <DialogFooter>
                                <Button variant="outline" onClick={() => setIsDialogOpen(false)}>{t('admin.users.create_dialog.cancel')}</Button>
                                <Button onClick={handleCreate} disabled={creating}>
                                    {creating && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
                                    {t('admin.users.create_dialog.submit')}
                                </Button>
                            </DialogFooter>
                        </DialogContent>
                    </Dialog>
                </div>

                {/* Edit / View Dialog */}
                <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
                    <DialogContent className="max-w-md max-h-[85vh] overflow-y-auto">
                        <DialogHeader>
                            <DialogTitle>{viewing ? t('admin.users.edit_dialog.title_view') : t('admin.users.edit_dialog.title_edit')}</DialogTitle>
                            <DialogDescription>{viewing ? t('admin.users.edit_dialog.description_view') : t('admin.users.edit_dialog.description_edit')}</DialogDescription>
                        </DialogHeader>
                        <div className="grid gap-4 py-4">
                            <div className="grid gap-2">
                                <Label htmlFor="edit-name">{t('admin.users.table.name')}</Label>
                                <Input
                                    id="edit-name"
                                    value={editFormData.name}
                                    onChange={(e) => setEditFormData({ ...editFormData, name: e.target.value })}
                                    placeholder={t('admin.users.table.name')}
                                    readOnly={viewing}
                                    disabled={viewing}
                                />
                            </div>
                            <div className="grid gap-2">
                                <Label htmlFor="edit-email">{t('admin.users.table.email')}</Label>
                                <Input
                                    id="edit-email"
                                    type="email"
                                    value={editFormData.email}
                                    onChange={(e) => setEditFormData({ ...editFormData, email: e.target.value })}
                                    placeholder={t('admin.users.table.email')}
                                    readOnly={viewing}
                                    disabled={viewing}
                                />
                            </div>
                            <div className="grid gap-2">
                                <Label htmlFor="edit-role">Role</Label>
                                <Select
                                    value={editFormData.role}
                                    onValueChange={(v) => setEditFormData({ ...editFormData, role: v })}
                                    disabled={viewing}
                                >
                                    <SelectTrigger>
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="superadmin">Super Admin</SelectItem>
                                        <SelectItem value="admin">Company admin</SelectItem>
                                        <SelectItem value="recruiter">Recruiter</SelectItem>
                                        <SelectItem value="candidate">Candidate</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>
                            <div className="grid gap-2">
                                <Label htmlFor="edit-status">Status</Label>
                                <Select
                                    value={editFormData.status}
                                    onValueChange={(v) => setEditFormData({ ...editFormData, status: v })}
                                    disabled={viewing}
                                >
                                    <SelectTrigger>
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="active">Active</SelectItem>
                                        <SelectItem value="inactive">Inactive</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>
                        </div>
                        <DialogFooter>
                            {viewing ? (
                                <>
                                    <Button variant="outline" onClick={() => setIsEditDialogOpen(false)}>
                                        {t('admin.users.edit_dialog.close')}
                                    </Button>
                                    <Button onClick={() => setViewing(false)}>
                                        Edit
                                    </Button>
                                </>
                            ) : (
                                <>
                                    <Button variant="outline" onClick={() => setIsEditDialogOpen(false)}>
                                        {t('admin.users.create_dialog.cancel')}
                                    </Button>
                                    <Button onClick={handleUpdate} disabled={updating}>
                                        {updating && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
                                        {t('admin.users.edit_dialog.save')}
                                    </Button>
                                </>
                            )}
                        </DialogFooter>
                    </DialogContent>
                </Dialog>

                {/* Delete Confirmation Dialog */}
                <Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
                    <DialogContent>
                        <DialogHeader>
                            <DialogTitle>{t('admin.users.delete_confirm.title')}</DialogTitle>
                            <DialogDescription>
                                {t('admin.users.delete_confirm.description')}
                            </DialogDescription>
                        </DialogHeader>
                        <div className="py-4">
                            {selectedUser && (
                                <div className="text-sm border p-4 rounded-md bg-muted/50">
                                    <p><strong>Name:</strong> {selectedUser.name}</p>
                                    <p><strong>Email:</strong> {selectedUser.email}</p>
                                    <p><strong>ID:</strong> {selectedUser.id}</p>
                                </div>
                            )}
                        </div>
                        <DialogFooter>
                            <Button variant="outline" onClick={() => setIsDeleteDialogOpen(false)}>
                                {t('admin.users.delete_confirm.cancel')}
                            </Button>
                            <Button variant="destructive" onClick={confirmDelete} disabled={deleting}>
                                {deleting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
                                {t('admin.users.delete_confirm.confirm')}
                            </Button>
                        </DialogFooter>
                    </DialogContent>
                </Dialog>
            </div>


            {/* Stats */}
            <div className="grid gap-3 sm:gap-4 grid-cols-2 md:grid-cols-4">
                <Card>
                    <CardHeader className="pb-3">
                        <CardDescription>{t('admin.users.total')}</CardDescription>
                        <CardTitle className="text-3xl">{totalUsers}</CardTitle>
                    </CardHeader>
                </Card>
                <Card>
                    <CardHeader className="pb-3">
                        <CardDescription>{t('admin.users.admins')}</CardDescription>
                        <CardTitle className="text-3xl">
                            {users.filter((u) => u.role === "superadmin" || u.role === "admin" || u.role === "admin").length}
                        </CardTitle>
                    </CardHeader>
                </Card>
                <Card>
                    <CardHeader className="pb-3">
                        <CardDescription>{t('admin.users.recruiters')}</CardDescription>
                        <CardTitle className="text-3xl">{users.filter((u) => u.role === "recruiter").length}</CardTitle>
                    </CardHeader>
                </Card>
                <Card>
                    <CardHeader className="pb-3">
                        <CardDescription>{t('admin.users.candidates')}</CardDescription>
                        <CardTitle className="text-3xl">{users.filter((u) => u.role === "candidate" || u.role === "candidate").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={t('admin.users.search_placeholder')}
                                value={searchTerm}
                                onChange={(e) => setSearchTerm(e.target.value)}
                                className="pl-10"
                            />
                        </div>
                    </div>
                </CardHeader>
                <CardContent>
                    {loading ? (
                        <div className="space-y-2 py-4">
                            {[...Array(5)].map((_, i) => (
                                <div key={i} className="flex items-center space-x-4">
                                    <Skeleton className="h-12 w-full" />
                                </div>
                            ))}
                        </div>
                    ) : (
                        <div className="space-y-4">
                            <div className="overflow-x-auto -mx-4 sm:mx-0">
                                <Table className="min-w-[600px]">
                                    <TableHeader>
                                        <TableRow>
                                            <TableHead>{t('admin.users.table.name')}</TableHead>
                                            <TableHead className="hidden sm:table-cell">{t('admin.users.table.email')}</TableHead>
                                            <TableHead>{t('admin.users.table.role')}</TableHead>
                                            <TableHead className="hidden md:table-cell">{t('admin.users.table.status')}</TableHead>
                                            <TableHead className="hidden lg:table-cell">{t('admin.users.table.created')}</TableHead>
                                            <TableHead className="text-right">{t('admin.users.table.actions')}</TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {filteredUsers.length === 0 ? (
                                            <TableRow>
                                                <TableCell colSpan={6} className="text-center text-muted-foreground py-8">
                                                    {t('admin.users.table.no_users')}
                                                </TableCell>
                                            </TableRow>
                                        ) : (
                                            filteredUsers.map((user) => (
                                                <TableRow key={user.id}>
                                                    <TableCell className="font-medium">{user.name}</TableCell>
                                                    <TableCell className="hidden sm:table-cell">{user.email}</TableCell>
                                                    <TableCell>{getRoleBadge(user.role)}</TableCell>
                                                    <TableCell className="hidden md:table-cell">
                                                        <Badge
                                                            variant="outline"
                                                            className={
                                                                user.status === "active"
                                                                    ? "border-transparent bg-green-500/15 text-green-700 hover:bg-green-500/25 dark:text-green-400"
                                                                    : "border-transparent bg-red-500/15 text-red-700 hover:bg-red-500/25 dark:text-red-400"
                                                            }
                                                        >
                                                            {user.status ? user.status.toUpperCase() : "UNKNOWN"}
                                                        </Badge>
                                                    </TableCell>
                                                    <TableCell className="hidden lg:table-cell">
                                                        {user.created_at ? userDateFormatter.format(new Date(user.created_at)) : "-"}
                                                    </TableCell>
                                                    <TableCell className="text-right">
                                                        <div className="flex justify-end gap-2">
                                                            <Button
                                                                variant="ghost"
                                                                size="icon"
                                                                onClick={() => handleView(user)}
                                                                title="View Details"
                                                            >
                                                                <Eye className="h-4 w-4" />
                                                            </Button>
                                                            <Button
                                                                variant="ghost"
                                                                size="icon"
                                                                onClick={() => handleEdit(user)}
                                                                disabled={user.role === "superadmin"}
                                                            >
                                                                <Pencil className="h-4 w-4" />
                                                            </Button>
                                                            <Button
                                                                variant="ghost"
                                                                size="icon"
                                                                onClick={() => handleDeleteClick(user)}
                                                                disabled={user.role === "superadmin"}
                                                            >
                                                                <Trash2 className="h-4 w-4 text-destructive" />
                                                            </Button>
                                                        </div>
                                                    </TableCell>
                                                </TableRow>
                                            ))
                                        )}
                                    </TableBody>
                                </Table>
                            </div>
                            <div className="flex flex-col sm:flex-row items-center justify-between gap-3 text-sm text-muted-foreground pt-4">
                                <span className="text-center sm:text-left">
                                    {totalUsers === 0
                                        ? t('admin.users.pagination.no_users_display')
                                        : t('admin.users.pagination.showing', { start: (page - 1) * limit + 1, end: Math.min(page * limit, totalUsers), total: totalUsers })}
                                </span>
                                <div className="flex items-center gap-2">
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() => loadUsers(page - 1)}
                                        disabled={page <= 1 || loading}
                                    >
                                        {t('admin.users.pagination.previous')}
                                    </Button>
                                    <span>
                                        {t('admin.users.pagination.page', { current: page, total: totalPages })}
                                    </span>
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() => loadUsers(page + 1)}
                                        disabled={page >= totalPages || loading}
                                    >
                                        {t('admin.users.pagination.next')}
                                    </Button>
                                </div>
                            </div>
                        </div>
                    )}
                </CardContent>
            </Card>
        </div>
    )
}
