"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, isAdminUser } from "@/lib/auth"
import { toast } from "sonner"
import { Skeleton } from "@/components/ui/skeleton"

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

export default function AdminUsersPage() {
    const router = useRouter()
    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 [creating, setCreating] = useState(false)
    const [updating, setUpdating] = useState(false)
    const [selectedUser, setSelectedUser] = useState<ApiUser | null>(null)
    const [formData, setFormData] = useState({
        name: "",
        email: "",
        password: "",
        role: "jobSeeker",
    })
    const [editFormData, setEditFormData] = useState({
        name: "",
        email: "",
    })

    useEffect(() => {
        const user = getCurrentUser()
        if (!isAdminUser(user)) {
            router.push("/dashboard")
            return
        }
        loadUsers()
    }, [router])

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

    const loadUsers = async (targetPage = page) => {
        try {
            setLoading(true)
            const data = await usersApi.list({ page: targetPage, limit })
            setUsers(data?.data || [])
            setTotalUsers(data?.pagination?.total || 0)
            setPage(data?.pagination?.page || targetPage)
        } catch (error) {
            console.error("Error loading users:", error)
            toast.error("Failed to load users")
        } finally {
            setLoading(false)
        }
    }

    const handleCreate = async () => {
        try {
            setCreating(true)
            await usersApi.create(formData)
            toast.success("User created successfully!")
            setIsDialogOpen(false)
            setFormData({ name: "", email: "", password: "", role: "jobSeeker" })
            setPage(1)
            loadUsers(1)
        } catch (error) {
            console.error("Error creating user:", error)
            toast.error("Failed to create user")
        } finally {
            setCreating(false)
        }
    }

    const handleEdit = (user: ApiUser) => {
        setSelectedUser(user)
        setEditFormData({
            name: user.name,
            email: user.email,
        })
        setIsEditDialogOpen(true)
    }

    const handleUpdate = async () => {
        if (!selectedUser) return
        try {
            setUpdating(true)
            await usersApi.update(selectedUser.id, editFormData)
            toast.success("User updated successfully!")
            setIsEditDialogOpen(false)
            loadUsers() // Refresh list
        } catch (error) {
            console.error("Error updating user:", error)
            toast.error("Failed to update user")
        } finally {
            setUpdating(false)
        }
    }

    const handleDelete = async (id: string) => {
        // Optimistic UI update or wait? User asked for no full reload.
        // We can remove it from state immediately.
        // We should use a proper dialog but standard confirm is quick.
        if (!confirm("Are you sure you want to delete this user?")) return

        // Optimistic update
        const originalUsers = [...users]
        setUsers(users.filter(u => u.id !== id))

        try {
            await usersApi.delete(id)
            toast.success("User deleted!")
            // If we are on a page > 1 and it becomes empty, we might need to fetch prev page
            if (users.length === 1 && page > 1) {
                setPage(page - 1)
                loadUsers(page - 1)
            } else {
                // Background revalidate to ensure count is correct
                loadUsers(page)
            }
        } catch (error) {
            console.error("Error deleting user:", error)
            toast.error("Failed to delete user")
            setUsers(originalUsers) // Revert on failure
        }
    }

    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: "Company admin",
            recruiter: "Recruiter",
            jobSeeker: "Candidate",
            admin: "Admin",
            company: "Company"
        }
        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 || "User"
        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">User management</h1>
                    <p className="text-muted-foreground mt-1">Manage all platform users</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" : ""}`} />
                        Refresh
                    </Button>
                    <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                        <DialogTrigger asChild>
                            <Button className="gap-2">
                                <Plus className="h-4 w-4" />
                                New user
                            </Button>
                        </DialogTrigger>
                        <DialogContent>
                            <DialogHeader>
                                <DialogTitle>Create new user</DialogTitle>
                                <DialogDescription>Fill in the new user details</DialogDescription>
                            </DialogHeader>
                            <div className="grid gap-4 py-4">
                                <div className="grid gap-2">
                                    <Label htmlFor="name">Name</Label>
                                    <Input
                                        id="name"
                                        value={formData.name}
                                        onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                                        placeholder="Full name"
                                    />
                                </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@example.com"
                                    />
                                </div>
                                <div className="grid gap-2">
                                    <Label htmlFor="password">Password</Label>
                                    <Input
                                        id="password"
                                        type="password"
                                        value={formData.password}
                                        onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                                        placeholder="Secure password"
                                    />
                                </div>
                                <div className="grid gap-2">
                                    <Label htmlFor="role">Role</Label>
                                    <Select value={formData.role} onValueChange={(v) => setFormData({ ...formData, role: v })}>
                                        <SelectTrigger>
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="superadmin">Super Admin</SelectItem>
                                            <SelectItem value="companyAdmin">Company admin</SelectItem>
                                            <SelectItem value="recruiter">Recruiter</SelectItem>
                                            <SelectItem value="jobSeeker">Candidate</SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>
                            </div>
                            <DialogFooter>
                                <Button variant="outline" onClick={() => setIsDialogOpen(false)}>Cancel</Button>
                                <Button onClick={handleCreate} disabled={creating}>
                                    {creating && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
                                    Create user
                                </Button>
                            </DialogFooter>
                        </DialogContent>
                    </Dialog>
                </div>
                <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
                    <DialogContent>
                        <DialogHeader>
                            <DialogTitle>Edit User</DialogTitle>
                            <DialogDescription>Update user details</DialogDescription>
                        </DialogHeader>
                        <div className="grid gap-4 py-4">
                            <div className="grid gap-2">
                                <Label htmlFor="edit-name">Name</Label>
                                <Input
                                    id="edit-name"
                                    value={editFormData.name}
                                    onChange={(e) => setEditFormData({ ...editFormData, name: e.target.value })}
                                    placeholder="Full name"
                                />
                            </div>
                            <div className="grid gap-2">
                                <Label htmlFor="edit-email">Email</Label>
                                <Input
                                    id="edit-email"
                                    type="email"
                                    value={editFormData.email}
                                    onChange={(e) => setEditFormData({ ...editFormData, email: e.target.value })}
                                    placeholder="email@example.com"
                                />
                            </div>
                        </div>
                        <DialogFooter>
                            <Button variant="outline" onClick={() => setIsEditDialogOpen(false)}>Cancel</Button>
                            <Button onClick={handleUpdate} disabled={updating}>
                                {updating && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
                                Save Changes
                            </Button>
                        </DialogFooter>
                    </DialogContent>
                </Dialog>
            </div>


            {/* Stats */}
            <div className="grid gap-4 md:grid-cols-4">
                <Card>
                    <CardHeader className="pb-3">
                        <CardDescription>Total users</CardDescription>
                        <CardTitle className="text-3xl">{totalUsers}</CardTitle>
                    </CardHeader>
                </Card>
                <Card>
                    <CardHeader className="pb-3">
                        <CardDescription>Admins (page)</CardDescription>
                        <CardTitle className="text-3xl">
                            {users.filter((u) => u.role === "superadmin" || u.role === "companyAdmin").length}
                        </CardTitle>
                    </CardHeader>
                </Card>
                <Card>
                    <CardHeader className="pb-3">
                        <CardDescription>Recruiters (page)</CardDescription>
                        <CardTitle className="text-3xl">{users.filter((u) => u.role === "recruiter").length}</CardTitle>
                    </CardHeader>
                </Card>
                <Card>
                    <CardHeader className="pb-3">
                        <CardDescription>Candidates (page)</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="Search users by name or email..."
                                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">
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Name</TableHead>
                                        <TableHead>Email</TableHead>
                                        <TableHead>Role</TableHead>
                                        <TableHead>Status</TableHead>
                                        <TableHead>Created</TableHead>
                                        <TableHead className="text-right">Actions</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {filteredUsers.length === 0 ? (
                                        <TableRow>
                                            <TableCell colSpan={6} className="text-center text-muted-foreground py-8">
                                                No users found
                                            </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" ? "Active" : user.status}
                                                    </Badge>
                                                </TableCell>
                                                <TableCell>
                                                    {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={() => handleEdit(user)}
                                                            disabled={user.role === "superadmin"}
                                                        >
                                                            <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>
                            <div className="flex flex-wrap items-center justify-between gap-2 text-sm text-muted-foreground">
                                <span>
                                    {totalUsers === 0
                                        ? "No users to display"
                                        : `Showing ${(page - 1) * limit + 1}-${Math.min(page * limit, totalUsers)} of ${totalUsers}`}
                                </span>
                                <div className="flex items-center gap-2">
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() => loadUsers(page - 1)}
                                        disabled={page <= 1 || loading}
                                    >
                                        Previous
                                    </Button>
                                    <span>
                                        Page {page} of {totalPages}
                                    </span>
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() => loadUsers(page + 1)}
                                        disabled={page >= totalPages || loading}
                                    >
                                        Next
                                    </Button>
                                </div>
                            </div>
                        </div>
                    )}
                </CardContent>
            </Card>
        </div>
    )
}
