import React, { useState, useEffect } from 'react';
import { Head, router, Link, useForm } from '@inertiajs/react';
import AdminLayout from '@/cp/Layouts/AdminLayout';
import { Card, CardContent, CardHeader, CardTitle } from "@/Components/ui/card";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from "@/Components/ui/dialog";
import { MoreHorizontal, Shield, Store, Trash2, Search, AlertTriangle } from "lucide-react";
import { toast } from 'sonner';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/Components/ui/dropdown-menu";

export default function Index({ users, filters, auth }) {
    const currentUser = auth.user;

    // Search State
    const [search, setSearch] = useState(filters.search || '');

    // Modals State
    const [isDeleteOpen, setIsDeleteOpen] = useState(false);
    const [userToDelete, setUserToDelete] = useState(null);
    const [deleteConfirmText, setDeleteConfirmText] = useState('');
    
    const [isRoleModalOpen, setIsRoleModalOpen] = useState(false);

    // Role Form State
    const { data, setData, put, processing, reset, errors } = useForm({
        user_id: '',
        role: ''
    });

    // Handle Search Debounce
    useEffect(() => {
        const delay = setTimeout(() => {
            if (search !== filters.search) {
                router.get(route('cp.users.index'), { search }, { preserveState: true, replace: true });
            }
        }, 500);
        return () => clearTimeout(delay);
    }, [search]);

    // Open Role Editor
    const openRoleModal = (user) => {
        setData({
            user_id: user.id,
            role: user.role === 'user' ? 'buyer' : user.role, // Map 'user' to 'buyer' for UI clarity
        });
        setIsRoleModalOpen(true);
    };

    // Submit Role Update
    const handleRoleUpdate = (e) => {
        e.preventDefault();
        put(route('cp.users.role.update', data.user_id), {
            preserveScroll: true,
            onSuccess: () => {
                toast.success('Permissions updated successfully.');
                setIsRoleModalOpen(false);
                reset();
            }
        });
    };

    // Open Delete Modal
    const openDeleteModal = (user) => {
        setUserToDelete(user);
        setDeleteConfirmText(''); // Reset the input field
        setIsDeleteOpen(true);
    };

    // Delete Logic
    const executeDelete = () => {
        if (!userToDelete || deleteConfirmText !== userToDelete.username) return;
        
        router.delete(route('cp.users.destroy', userToDelete.id), {
            preserveScroll: true,
            onSuccess: () => {
                toast.success("User deleted successfully.");
                setIsDeleteOpen(false);
            }
        });
    };

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

            {/* --- CUSTOM DELETE CONFIRMATION MODAL WITH USERNAME VERIFICATION --- */}
            <Dialog open={isDeleteOpen} onOpenChange={setIsDeleteOpen}>
                <DialogContent className="sm:max-w-md border-destructive/20 shadow-2xl flex flex-col max-h-[90vh] overflow-hidden p-0 sm:rounded-2xl">
                    <div className="flex flex-col flex-1 min-h-0 overflow-hidden">
                        <DialogHeader className="p-4 sm:p-6 pb-4 border-b shrink-0 bg-muted/10">
                            <DialogTitle className="text-destructive flex items-center gap-2">
                                <AlertTriangle className="w-5 h-5" /> Delete User Account
                            </DialogTitle>
                            <DialogDescription className="pt-2 text-foreground">
                                This action cannot be undone. This will permanently delete <strong>{userToDelete?.name}</strong> and all associated data, including products and orders.
                            </DialogDescription>
                        </DialogHeader>
                        
                        <div className="p-4 sm:p-6 py-4 space-y-3 overflow-y-auto flex-1 min-h-0">
                            <Label className="text-sm">
                                Please type <span className="font-mono font-bold text-red-600 bg-red-500/10 px-1.5 py-0.5 rounded select-all">{userToDelete?.username}</span> to confirm.
                            </Label>
                            <Input 
                                value={deleteConfirmText} 
                                onChange={e => setDeleteConfirmText(e.target.value)}
                                placeholder={userToDelete?.username}
                                className="bg-background border-input font-mono"
                                autoComplete="off"
                            />
                        </div>

                        <DialogFooter className="p-4 border-t shrink-0 bg-muted/10 gap-2 sm:gap-0">
                            <Button variant="outline" onClick={() => setIsDeleteOpen(false)} className="w-full sm:w-auto">Cancel</Button>
                            <Button 
                                variant="destructive" 
                                onClick={executeDelete} 
                                disabled={deleteConfirmText !== userToDelete?.username}
                                className="w-full sm:w-auto"
                            >
                                Permanently Delete
                            </Button>
                        </DialogFooter>
                    </div>
                </DialogContent>
            </Dialog>

            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
                <div>
                    <h2 className="text-2xl sm:text-3xl font-bold tracking-tight">Roles & Privileges</h2>
                    <p className="text-muted-foreground text-sm sm:text-base">Manage users and assign seller roles.</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 
                        placeholder="Search users..." className="pl-9 bg-card shadow-sm"
                        value={search} onChange={(e) => setSearch(e.target.value)}
                    />
                </div>
            </div>

            <Card className="w-full border-border/50 shadow-sm overflow-hidden">
                <CardHeader className="p-4 border-b bg-muted/10">
                    <CardTitle className="text-lg">Registered Accounts</CardTitle>
                </CardHeader>
                <CardContent className="p-0">
                    <div className="w-full overflow-x-auto min-h-0">
                        <table className="w-full text-sm text-left">
                            <thead className="text-xs uppercase bg-muted/40 text-muted-foreground border-b whitespace-nowrap">
                                <tr>
                                    <th className="px-4 py-4 min-w-[200px]">User</th>
                                    <th className="px-4 py-4">Role</th>
                                    <th className="px-4 py-4 min-w-[150px]">Store Info</th>
                                    <th className="px-4 py-4">Joined</th>
                                    <th className="px-4 py-4 text-right">Actions</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-border">
                                {users.data.map((user) => (
                                    <tr key={user.id} className="bg-card hover:bg-muted/30 transition-colors">
                                        <td className="px-4 py-3 align-top">
                                            <div className="font-bold text-foreground flex items-center flex-wrap gap-2">
                                                <span className="truncate">{user.name}</span>
                                                {currentUser.id === user.id && <span className="text-[10px] bg-primary/20 text-primary px-2 py-0.5 rounded-full shrink-0">You</span>}
                                            </div>
                                            <div className="text-xs text-muted-foreground font-mono mt-0.5 truncate">@{user.username}</div>
                                            <div className="text-xs text-muted-foreground mt-0.5 truncate">{user.email}</div>
                                        </td>
                                        <td className="px-4 py-3 align-top">
                                            <span className={`inline-block px-2.5 py-1 rounded-full text-[10px] font-bold uppercase tracking-wider whitespace-nowrap ${
                                                user.role === 'admin' ? 'bg-red-500/10 text-red-600' : 
                                                user.role === 'seller' ? 'bg-blue-500/10 text-blue-600' :
                                                'bg-zinc-500/10 text-zinc-600'
                                            }`}>
                                                {user.role === 'user' ? 'Buyer' : user.role}
                                            </span>
                                        </td>
                                        <td className="px-4 py-3 text-xs text-muted-foreground align-top">
                                            {user.role === 'seller' && user.company_name ? (
                                                <span className="flex items-start sm:items-center gap-1.5 font-semibold text-foreground">
                                                    <Store className="w-3.5 h-3.5 text-blue-500 shrink-0 mt-0.5 sm:mt-0"/> 
                                                    <span className="line-clamp-2">{user.company_name}</span>
                                                </span>
                                            ) : <span>-</span>}
                                        </td>
                                        <td className="px-4 py-3 text-xs text-muted-foreground align-top whitespace-nowrap">
                                            {new Date(user.created_at).toLocaleDateString()}
                                        </td>
                                        <td className="px-4 py-3 text-right align-top">
                                            {currentUser.id !== user.id && (
                                                <DropdownMenu>
                                                    <DropdownMenuTrigger className="h-8 w-8 inline-flex items-center justify-center rounded-md hover:bg-muted outline-none">
                                                        <MoreHorizontal className="h-4 w-4" />
                                                    </DropdownMenuTrigger>
                                                    <DropdownMenuContent align="end" className="w-48 shadow-lg rounded-xl">
                                                        <DropdownMenuLabel>Actions</DropdownMenuLabel>
                                                        <DropdownMenuSeparator />
                                                        <DropdownMenuItem onClick={() => openRoleModal(user)} className="cursor-pointer py-2">
                                                            <Shield className="mr-2 h-4 w-4 text-primary" /> Edit Privileges
                                                        </DropdownMenuItem>
                                                        <DropdownMenuItem onClick={() => openDeleteModal(user)} className="text-destructive cursor-pointer py-2">
                                                            <Trash2 className="mr-2 h-4 w-4" /> Delete User
                                                        </DropdownMenuItem>
                                                    </DropdownMenuContent>
                                                </DropdownMenu>
                                            )}
                                        </td>
                                    </tr>
                                ))}
                                {users.data.length === 0 && (
                                    <tr>
                                        <td colSpan="5" className="px-4 py-12 text-center text-muted-foreground">
                                            No users found.
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </CardContent>
            </Card>

            {/* Pagination Controls */}
            {users.links?.length > 3 && (
                <div className="flex flex-col sm:flex-row justify-between items-center mt-6 bg-card p-4 rounded-xl border border-border/50 shadow-sm gap-4">
                    <span className="text-xs text-muted-foreground font-medium shrink-0">
                        Showing {users.from || 0} to {users.to || 0} of {users.total} users
                    </span>
                    <div className="flex gap-1 overflow-x-auto no-scrollbar w-full sm:w-auto pb-2 sm:pb-0">
                        {users.links.map((link, i) => (
                            <Link
                                key={i}
                                href={link.url || '#'}
                                className={`px-3 py-1.5 border rounded-md text-xs transition-all shrink-0 ${link.active ? 'bg-primary text-primary-foreground border-primary shadow-sm font-bold' : 'bg-background hover:bg-muted text-foreground'} ${!link.url && 'opacity-30 cursor-not-allowed'}`}
                                dangerouslySetInnerHTML={{ __html: link.label }}
                            />
                        ))}
                    </div>
                </div>
            )}

            {/* ROLE & PRIVILEGE MODAL */}
            <Dialog open={isRoleModalOpen} onOpenChange={setIsRoleModalOpen}>
                <DialogContent className="sm:max-w-md flex flex-col p-0 overflow-hidden max-h-[90vh] sm:rounded-2xl">
                    <form onSubmit={handleRoleUpdate} className="flex flex-col flex-1 min-h-0 overflow-hidden">
                        <DialogHeader className="p-4 sm:p-6 pb-4 border-b shrink-0 bg-muted/10">
                            <DialogTitle>Edit User Privileges</DialogTitle>
                            <DialogDescription>Change the system role for this account.</DialogDescription>
                        </DialogHeader>
                        
                        <div className="p-4 sm:p-6 py-4 space-y-6 overflow-y-auto flex-1 min-h-0 custom-scrollbar">
                            <div className="space-y-2">
                                <Label>Account Role</Label>
                                <Select value={data.role} onValueChange={(val) => setData('role', val)}>
                                    <SelectTrigger>
                                        <SelectValue placeholder="Select a role" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="buyer">Buyer (Standard User)</SelectItem>
                                        <SelectItem value="seller">Seller (Store Owner)</SelectItem>
                                        <SelectItem value="admin">Administrator (Full Access)</SelectItem>
                                    </SelectContent>
                                </Select>
                                {errors.role && <p className="text-xs text-destructive">{errors.role}</p>}
                            </div>
                        </div>

                        <DialogFooter className="p-4 border-t shrink-0 bg-muted/10 gap-2 sm:gap-0">
                            <Button type="button" variant="outline" onClick={() => setIsRoleModalOpen(false)} className="w-full sm:w-auto">Cancel</Button>
                            <Button type="submit" disabled={processing} className="w-full sm:w-auto">Save Privileges</Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>

        </AdminLayout>
    );
}