import { useEffect, useState } from 'react';
import { Head } from '@inertiajs/react';
import axios from 'axios';
import { toast } from 'sonner';
import { 
    Search, MoreHorizontal, Trash2, ShieldAlert, Copy, 
    Pencil, Mail, Shield, User as UserIcon, Loader2, 
    ExternalLink, FileText 
} from 'lucide-react';
import AdminLayout from '@/Admin/Layouts/AdminLayout';

import { Input } from '@/Components/ui/input';
import { Button } from '@/Components/ui/button';
import { Badge } from '@/Components/ui/badge';
import { Label } from '@/Components/ui/label';
import { Avatar, AvatarFallback, AvatarImage } from '@/Components/ui/avatar';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/Components/ui/table";
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuLabel,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from "@/Components/ui/dropdown-menu";
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from "@/Components/ui/dialog";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/Components/ui/select";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/Components/ui/card';
import ConfirmModal from '@/Components/ConfirmModal'; 

export default function UserList() {
    // --- State ---
    const [users, setUsers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [search, setSearch] = useState('');
    const [page, setPage] = useState(1);
    const [pagination, setPagination] = useState({});

    // Delete Modal
    const [deleteId, setDeleteId] = useState(null);
    const [isDeleteOpen, setIsDeleteOpen] = useState(false);

    // Edit Modal
    const [isEditOpen, setIsEditOpen] = useState(false);
    const [editingUser, setEditingUser] = useState(null);
    const [editForm, setEditForm] = useState({ name: '', email: '', role: 'user' });
    const [isSaving, setIsSaving] = useState(false);

    // --- Data Fetching ---
    const fetchUsers = async () => {
        setLoading(true);
        try {
            const response = await axios.get(`/api/admin/users?page=${page}&search=${search}`);
            setUsers(response.data.data);
            setPagination(response.data);
        } catch (error) {
            console.error(error);
            toast.error("Failed to load users");
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        const timer = setTimeout(() => {
            fetchUsers();
        }, 300); 
        return () => clearTimeout(timer);
    }, [search, page]);

    // --- Handlers ---

    // 1. Delete Logic
    const handleDelete = async () => {
        if (!deleteId) return;
        try {
            await axios.delete(`/api/admin/users/${deleteId}`);
            toast.success("User deleted successfully");
            fetchUsers();
        } catch (error) {
            toast.error(error.response?.data?.message || "Failed to delete user");
        } finally {
            setIsDeleteOpen(false);
            setDeleteId(null);
        }
    };

    // 2. Edit Logic
    const openEditModal = (user) => {
        setEditingUser(user);
        setEditForm({ name: user.name, email: user.email, role: user.role });
        setIsEditOpen(true);
    };

    const handleUpdateUser = async (e) => {
        e.preventDefault();
        setIsSaving(true);
        try {
            await axios.put(`/api/admin/users/${editingUser.id}`, editForm);
            toast.success("User updated successfully");
            setIsEditOpen(false);
            fetchUsers();
        } catch (error) {
            if(error.response?.data?.errors) {
                // Show first validation error
                const firstError = Object.values(error.response.data.errors)[0][0];
                toast.error(firstError);
            } else {
                toast.error(error.response?.data?.message || "Update failed");
            }
        } finally {
            setIsSaving(false);
        }
    };

    // Helper: Role Badge Style
    const getRoleBadge = (role) => {
        switch(role) {
            case 'admin':
                return <Badge variant="destructive" className="gap-1"><ShieldAlert className="w-3 h-3" /> Admin</Badge>;
            default:
                return <Badge variant="secondary" className="gap-1"><UserIcon className="w-3 h-3" /> User</Badge>;
        }
    };

    return (
        <AdminLayout>
            <Head title="User Management" />

            <ConfirmModal 
                open={isDeleteOpen}
                onOpenChange={setIsDeleteOpen}
                onConfirm={handleDelete}
                title="Delete User Account"
                description="Are you sure? This will permanently delete the user and their data."
                confirmText="Delete User"
                variant="destructive"
            />

            {/* --- Edit User Dialog --- */}
            <Dialog open={isEditOpen} onOpenChange={setIsEditOpen}>
                <DialogContent className="sm:max-w-[425px]">
                    <DialogHeader>
                        <DialogTitle>Edit User</DialogTitle>
                        <DialogDescription>
                            Update profile details and assign roles.
                        </DialogDescription>
                    </DialogHeader>
                    <form onSubmit={handleUpdateUser} className="space-y-4 py-4">
                        <div className="space-y-2">
                            <Label>Full Name</Label>
                            <Input 
                                value={editForm.name} 
                                onChange={(e) => setEditForm({...editForm, name: e.target.value})} 
                                required 
                            />
                        </div>
                        <div className="space-y-2">
                            <Label>Email Address</Label>
                            <Input 
                                type="email" 
                                value={editForm.email} 
                                onChange={(e) => setEditForm({...editForm, email: e.target.value})} 
                                required 
                            />
                        </div>
                        <div className="space-y-2">
                            <Label>System Role</Label>
                            <Select 
                                value={editForm.role} 
                                onValueChange={(val) => setEditForm({...editForm, role: val})}
                            >
                                <SelectTrigger>
                                    <SelectValue placeholder="Select a role" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="user">
                                        <div className="flex items-center gap-2"><UserIcon className="w-4 h-4"/> User</div>
                                    </SelectItem>
                                    {/* Editor option removed as requested */}
                                    <SelectItem value="admin">
                                        <div className="flex items-center gap-2 text-red-600"><Shield className="w-4 h-4"/> Administrator</div>
                                    </SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                        <DialogFooter>
                            <Button type="button" variant="outline" onClick={() => setIsEditOpen(false)}>Cancel</Button>
                            <Button type="submit" disabled={isSaving}>
                                {isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />} Save Changes
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>

            {/* --- Main Layout --- */}
            <div className="space-y-6">
                <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                    <div>
                        <h2 className="text-3xl font-bold tracking-tight">User Management</h2>
                        <p className="text-muted-foreground">Manage user access, roles, and permissions.</p>
                    </div>
                    <div className="relative w-full sm:w-[300px]">
                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                        <Input 
                            type="text" 
                            placeholder="Search name, email, username..." 
                            className="pl-9"
                            value={search}
                            onChange={(e) => { setSearch(e.target.value); setPage(1); }}
                        />
                    </div>
                </div>

                <Card>
                    <CardHeader className="p-4 border-b">
                        <CardTitle className="text-lg">Registered Users</CardTitle>
                        <CardDescription>Total: {pagination.total || 0} users found</CardDescription>
                    </CardHeader>
                    <CardContent className="p-0">
                        <Table>
                            <TableHeader>
                                <TableRow className="bg-muted/50">
                                    <TableHead className="w-[60px] pl-4">Avatar</TableHead>
                                    <TableHead>User Details</TableHead>
                                    <TableHead className="text-center">Posts</TableHead>
                                    <TableHead>Role</TableHead>
                                    <TableHead className="hidden md:table-cell">Joined</TableHead>
                                    <TableHead className="text-right pr-4">Actions</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {loading ? (
                                    <TableRow>
                                        <TableCell colSpan={6} className="h-32 text-center text-muted-foreground">
                                            <div className="flex justify-center items-center gap-2"><Loader2 className="animate-spin h-5 w-5" /> Loading users...</div>
                                        </TableCell>
                                    </TableRow>
                                ) : users.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={6} className="h-32 text-center text-muted-foreground">
                                            No users found matching your search.
                                        </TableCell>
                                    </TableRow>
                                ) : (
                                    users.map((user) => (
                                        <TableRow key={user.id} className="group hover:bg-muted/50 transition-colors">
                                            <TableCell className="pl-4 py-3">
                                                <Avatar className="h-9 w-9 border">
                                                    <AvatarImage src={user.avatar || `https://ui-avatars.com/api/?name=${user.name}&background=random`} />
                                                    <AvatarFallback>{user.name.substring(0, 2).toUpperCase()}</AvatarFallback>
                                                </Avatar>
                                            </TableCell>
                                            <TableCell>
                                                <div className="flex flex-col">
                                                    <span className="font-medium text-sm">{user.name}</span>
                                                    <span className="text-xs text-muted-foreground font-mono">@{user.username}</span>
                                                    <div className="flex items-center gap-1 text-xs text-muted-foreground mt-0.5">
                                                        <Mail className="w-3 h-3" /> {user.email}
                                                    </div>
                                                </div>
                                            </TableCell>
                                            {/* Post Count Column */}
                                            <TableCell className="text-center">
                                                <Badge variant="outline" className="font-mono">
                                                    <FileText className="w-3 h-3 mr-1 text-muted-foreground" />
                                                    {user.posts_count || 0}
                                                </Badge>
                                            </TableCell>
                                            <TableCell>
                                                {getRoleBadge(user.role)}
                                            </TableCell>
                                            <TableCell className="hidden md:table-cell text-sm text-muted-foreground">
                                                {new Date(user.created_at).toLocaleDateString()}
                                            </TableCell>
                                            <TableCell className="text-right pr-4">
                                                <DropdownMenu>
                                                    <DropdownMenuTrigger asChild>
                                                        <Button variant="ghost" size="icon" className="h-8 w-8">
                                                            <MoreHorizontal className="h-4 w-4" />
                                                            <span className="sr-only">Open menu</span>
                                                        </Button>
                                                    </DropdownMenuTrigger>
                                                    <DropdownMenuContent align="end">
                                                        <DropdownMenuLabel>Actions</DropdownMenuLabel>
                                                        
                                                        {/* Public Profile Link */}
                                                        <DropdownMenuItem asChild>
                                                            <a 
                                                                href={route('author.show', user.username || '#')} 
                                                                target="_blank" 
                                                                rel="noopener noreferrer"
                                                                className="cursor-pointer"
                                                            >
                                                                <ExternalLink className="mr-2 h-4 w-4" /> View Public Profile
                                                            </a>
                                                        </DropdownMenuItem>

                                                        <DropdownMenuItem onClick={() => {
                                                            navigator.clipboard.writeText(user.email);
                                                            toast.success("Email copied");
                                                        }}>
                                                            <Copy className="mr-2 h-4 w-4" /> Copy Email
                                                        </DropdownMenuItem>
                                                        
                                                        <DropdownMenuSeparator />
                                                        
                                                        <DropdownMenuItem onClick={() => openEditModal(user)}>
                                                            <Pencil className="mr-2 h-4 w-4" /> Edit Role & Details
                                                        </DropdownMenuItem>
                                                        <DropdownMenuItem 
                                                            onClick={() => { setDeleteId(user.id); setIsDeleteOpen(true); }}
                                                            className="text-red-600 focus:text-red-600 focus:bg-red-50"
                                                        >
                                                            <Trash2 className="mr-2 h-4 w-4" /> Delete Account
                                                        </DropdownMenuItem>
                                                    </DropdownMenuContent>
                                                </DropdownMenu>
                                            </TableCell>
                                        </TableRow>
                                    ))
                                )}
                            </TableBody>
                        </Table>
                    </CardContent>
                </Card>

                {/* Pagination */}
                <div className="flex items-center justify-end space-x-2">
                    <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setPage(p => Math.max(1, p - 1))}
                        disabled={!pagination.prev_page_url || loading}
                    >
                        Previous
                    </Button>
                    <span className="text-sm text-muted-foreground">
                        Page {pagination.current_page} of {pagination.last_page}
                    </span>
                    <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setPage(p => p + 1)}
                        disabled={!pagination.next_page_url || loading}
                    >
                        Next
                    </Button>
                </div>
            </div>
        </AdminLayout>
    );
}