import { useQuery, useMutation } from "@tanstack/react-query";
import { User } from "@shared/schema";
import { apiRequest, queryClient } from "@/lib/queryClient";
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { useToast } from "@/hooks/use-toast";
import { useTranslation } from "react-i18next";
import { Card, CardHeader, CardTitle, CardContent, CardDescription } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Plus, Shield, User as UserIcon } from "lucide-react";
import { useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from "@/components/ui/alert-dialog";

export default function AdminUserManagement() {
    const { t } = useTranslation();
    const { toast } = useToast();
    const [isCreateOpen, setIsCreateOpen] = useState(false);
    const [newUser, setNewUser] = useState({ username: '', email: '', password: '', role: 'user' });

    // Queries
    const { data: users = [], isLoading } = useQuery<User[]>({
        queryKey: ["/api/admin/users"],
    });

    const { data: settings } = useQuery<{ registration_enabled: boolean }>({
        queryKey: ["/api/admin/settings"],
    });

    // Delete User State
    const [deleteUser, setDeleteUser] = useState<User | null>(null);
    const [confirmText, setConfirmText] = useState("");

    // Mutations
    const toggleActiveMutation = useMutation({
        mutationFn: (userId: string) => apiRequest("POST", `/api/admin/users/${userId}/toggle-active`),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["/api/admin/users"] });
            toast({ title: "User status updated" });
        },
        onError: (e: Error) => toast({ title: "Failed to update", description: e.message, variant: "destructive" }),
    });

    const updateSettingsMutation = useMutation({
        mutationFn: (data: Partial<typeof settings>) => apiRequest("POST", "/api/admin/settings", data),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["/api/admin/settings"] });
            toast({ title: t('userManagement.settingsUpdated', 'Settings updated') });
        },
    });

    const deleteUserMutation = useMutation({
        mutationFn: (userId: string) => apiRequest("DELETE", `/api/admin/users/${userId}`),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["/api/admin/users"] });
            setDeleteUser(null);
            setConfirmText("");
            toast({ title: t('userManagement.userDeleted', 'User deleted') });
        },
        onError: (e: Error) => toast({ title: "Failed to delete", description: e.message, variant: "destructive" }),
    });

    const createUserMutation = useMutation({
        mutationFn: (data: typeof newUser) => apiRequest("POST", "/api/admin/users", data),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["/api/admin/users"] });
            setIsCreateOpen(false);
            setNewUser({ username: '', email: '', password: '', role: 'user' });
            toast({ title: "User created" });
        },
        onError: (e: Error) => toast({ title: "Failed to create", description: e.message, variant: "destructive" }),
    });

    const [resetXpUser, setResetXpUser] = useState<User | null>(null);

    const resetXpMutation = useMutation({
        mutationFn: (userId: string) => apiRequest("POST", `/api/admin/users/${userId}/reset-xp`),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["/api/admin/users"] });
            setResetXpUser(null);
            toast({ title: t('userManagement.resetXpSuccess', 'User XP reset successfully') });
        },
        onError: (e: Error) => toast({ title: "Failed to reset XP", description: e.message, variant: "destructive" }),
    });

    return (
        <div className="space-y-6 container mx-auto p-4 max-w-5xl">
            <div className="flex justify-between items-center">
                <h1 className="text-3xl font-bold tracking-tight">{t('userManagement.title')}</h1>
            </div>

            {/* Global Settings (Registration Only now) */}
            <div className="grid gap-6 md:grid-cols-2">
                <Card>
                    <CardHeader>
                        <CardTitle>{t('userManagement.registration')}</CardTitle>
                        <CardDescription>{t('userManagement.registrationDesc')}</CardDescription>
                    </CardHeader>
                    <CardContent className="flex items-center justify-between">
                        <div className="space-y-1">
                            <p className="font-medium">{t('userManagement.publicRegistration')}</p>
                            <p className="text-sm text-muted-foreground">{t('userManagement.publicRegistrationDesc')}</p>
                        </div>
                        <Switch
                            checked={settings?.registration_enabled}
                            onCheckedChange={(checked) => updateSettingsMutation.mutate({ registration_enabled: checked })}
                        />
                    </CardContent>
                </Card>
            </div>

            {/* User Table */}
            <Card>
                <CardHeader className="flex flex-row items-center justify-between">
                    <div>
                        <CardTitle>{t('userManagement.registeredUsers')}</CardTitle>
                        <CardDescription>{t('userManagement.registeredUsersDesc')}</CardDescription>
                    </div>
                    <Dialog open={isCreateOpen} onOpenChange={setIsCreateOpen}>
                        <DialogTrigger asChild>
                            <Button><Plus className="mr-2 h-4 w-4" /> {t('userManagement.createUser')}</Button>
                        </DialogTrigger>
                        <DialogContent>
                            <DialogHeader>
                                <DialogTitle>{t('userManagement.createUser')}</DialogTitle>
                            </DialogHeader>
                            <div className="space-y-4 py-4">
                                <div className="space-y-2">
                                    <Label>{t('settings.account.username')}</Label>
                                    <Input value={newUser.username} onChange={e => setNewUser({ ...newUser, username: e.target.value })} />
                                </div>
                                <div className="space-y-2">
                                    <Label>{t('auth.email')}</Label>
                                    <Input value={newUser.email} onChange={e => setNewUser({ ...newUser, email: e.target.value })} />
                                </div>
                                <div className="space-y-2">
                                    <Label>{t('auth.password')}</Label>
                                    <Input type="password" value={newUser.password} onChange={e => setNewUser({ ...newUser, password: e.target.value })} />
                                </div>
                                <div className="space-y-2">
                                    <Label>{t('userManagement.table.role')}</Label>
                                    <select
                                        className="w-full p-2 border rounded-md bg-background"
                                        value={newUser.role}
                                        onChange={e => setNewUser({ ...newUser, role: e.target.value })}
                                    >
                                        <option value="user">{t('userManagement.roles.user')}</option>
                                        <option value="admin">{t('userManagement.roles.admin')}</option>
                                    </select>
                                </div>
                                <Button
                                    onClick={() => createUserMutation.mutate(newUser)}
                                    disabled={createUserMutation.isPending}
                                    className="w-full"
                                >
                                    {createUserMutation.isPending ? t('common.loading') : t('userManagement.createUser')}
                                </Button>
                            </div>
                        </DialogContent>
                    </Dialog>
                </CardHeader>
                <CardContent>
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead>{t('userManagement.table.user')}</TableHead>
                                <TableHead>{t('userManagement.table.role')}</TableHead>
                                <TableHead>{t('userManagement.table.status')}</TableHead>
                                <TableHead>{t('userManagement.table.xp')}</TableHead>
                                <TableHead className="text-right">{t('userManagement.table.actions')}</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {isLoading ? (
                                <TableRow>
                                    <TableCell colSpan={5} className="text-center h-24">{t('common.loading')}</TableCell>
                                </TableRow>
                            ) : users.map((user) => (
                                <TableRow key={user.id}>
                                    <TableCell>
                                        <div className="flex flex-col">
                                            <span className="font-medium">{user.username}</span>
                                            <span className="text-xs text-muted-foreground">{user.email}</span>
                                        </div>
                                    </TableCell>
                                    <TableCell>
                                        {user.role === 'admin' ? (
                                            <Badge variant="default" className="bg-primary/20 text-primary hover:bg-primary/30">
                                                <Shield className="w-3 h-3 mr-1" /> {t('userManagement.roles.admin')}
                                            </Badge>
                                        ) : (
                                            <Badge variant="outline">
                                                <UserIcon className="w-3 h-3 mr-1" /> {t('userManagement.roles.user')}
                                            </Badge>
                                        )}
                                    </TableCell>
                                    <TableCell>
                                        {user.isActive ? (
                                            <Badge variant="secondary" className="bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-100">{t('userManagement.table.active')}</Badge>
                                        ) : (
                                            <Badge variant="destructive">{t('userManagement.table.inactive')}</Badge>
                                        )}
                                    </TableCell>
                                    <TableCell>
                                        {user.xp} XP ({t('gamification.level', { level: user.level })})
                                    </TableCell>
                                    <TableCell className="text-right flex items-center justify-end gap-2">
                                        <Button
                                            variant={user.isActive ? "destructive" : "outline"}
                                            size="sm"
                                            onClick={() => toggleActiveMutation.mutate(user.id)}
                                            disabled={user.role === 'admin' && user.username === 'admin'}
                                        >
                                            {user.isActive ? t('userManagement.table.deactivate') : t('userManagement.table.activate')}
                                        </Button>
                                        <Button
                                            variant="outline"
                                            size="sm"
                                            onClick={() => setResetXpUser(user)}
                                            disabled={user.role === 'admin' && user.username === 'admin'}
                                        >
                                            {t('userManagement.resetXp', 'Reset XP')}
                                        </Button>
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            className="text-destructive hover:text-destructive"
                                            onClick={() => setDeleteUser(user)}
                                            disabled={user.role === 'admin' && user.username === 'admin'}
                                        >
                                            {t('common.delete')}
                                        </Button>
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                </CardContent>
            </Card>

            <Dialog open={!!deleteUser} onOpenChange={(open) => !open && setDeleteUser(null)}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>{t('userManagement.deleteUser')}</DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4 py-2">
                        <p className="text-sm text-muted-foreground">
                            {t('userManagement.deleteConfirm', { username: deleteUser?.username })}
                        </p>
                        <Label>{t('userManagement.typeToConfirm')}: <span className="font-bold select-all">{deleteUser?.username}</span></Label>
                        <Input
                            value={confirmText}
                            onChange={(e) => setConfirmText(e.target.value)}
                            placeholder={deleteUser?.username}
                        />
                        <div className="flex justify-end gap-2 pt-2">
                            <Button variant="outline" onClick={() => setDeleteUser(null)}>{t('common.cancel')}</Button>
                            <Button
                                variant="destructive"
                                onClick={() => deleteUser && deleteUserMutation.mutate(deleteUser.id)}
                                disabled={confirmText !== deleteUser?.username || deleteUserMutation.isPending}
                            >
                                {deleteUserMutation.isPending ? t('common.loading') : t('common.delete')}
                            </Button>
                        </div>
                    </div>
                </DialogContent>
            </Dialog>

            <AlertDialog open={!!resetXpUser} onOpenChange={(open) => !open && setResetXpUser(null)}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>{t('userManagement.resetXpTitle', 'Reset User XP')}</AlertDialogTitle>
                        <AlertDialogDescription>
                            {t('userManagement.resetXpConfirm', 'Are you sure you want to reset XP and Level for user "{username}"? This action cannot be undone.', { username: resetXpUser?.username })}
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel onClick={() => setResetXpUser(null)}>{t('common.cancel')}</AlertDialogCancel>
                        <AlertDialogAction
                            onClick={() => resetXpUser && resetXpMutation.mutate(resetXpUser.id)}
                            className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                        >
                            {resetXpMutation.isPending ? t('common.loading') : t('userManagement.resetXp', 'Reset XP')}
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </div>
    );
}
