function Login({ onLogin }) {
    const [users, setUsers] = React.useState([]);
    const [loading, setLoading] = React.useState(false);
    const [selectedUser, setSelectedUser] = React.useState(null);
    const [pin, setPin] = React.useState('');
    const [error, setError] = React.useState('');

    // Load users from backend on component mount
    React.useEffect(() => {
        const loadUsers = async () => {
            try {
                if (window.POSApiService) {
                    const res = await window.POSApiService.get('auth.php?action=get_all');
                    if (Array.isArray(res)) {
                        setUsers(res);
                    } else if (res.success && Array.isArray(res.data)) {
                        setUsers(res.data);
                    } else {
                        setUsers([]);
                        setError('No users returned from backend.');
                    }
                } else {
                    setUsers([]);
                    setError('Backend service not available.');
                }
            } catch (err) {
                console.warn('Failed to load users from backend:', err);
                setUsers([]);
                setError('Failed to connect to the backend server.');
            } finally {
                setLoading(false);
            }
        };
        
        loadUsers();
    }, []);

    const handleLogin = async (e) => {
        e.preventDefault();
        if (!selectedUser) return;

        if (window.POSApiService) {
            try {
                const res = await window.POSApiService.login(selectedUser.id, pin);
                if (res.success) {
                    onLogin(res.user);
                } else {
                    setError(res.message || res.error || 'Invalid credentials');
                    setPin('');
                }
            } catch (err) {
                console.error('Backend login failed.', err);
                setError('Failed to reach backend server. Please try again later.');
                setPin('');
            }
        } else {
            setError('Backend service not available.');
            setPin('');
        }
    };

    const handleUserSelect = (user) => {
        setSelectedUser(user);
        setError('');
        setPin('');
    };

    return (
        <div className="min-h-screen flex items-center justify-center bg-slate-900 relative overflow-hidden">
            {/* Background Pattern */}
            <div className="absolute inset-0 opacity-10">
                <div className="absolute top-0 left-0 w-full h-full bg-[url('https://www.transparenttextures.com/patterns/cubes.png')]"></div>
            </div>

            <div className="w-full max-w-md bg-white rounded-2xl shadow-2xl z-10 overflow-hidden">
                <div className="bg-black p-8 text-center relative">
                    <div className="w-40 h-24 mx-auto flex items-center justify-center mb-4">
                        <img src="components/Logo.png" alt="Logo" className="w-full h-full object-contain" />
                    </div>
                    <h1 className="text-2xl font-bold text-white tracking-tight">NOAHVELLE POS</h1>
                    <p className="text-emerald-100 text-sm mt-1">Retail Management System</p>
                </div>

                <div className="p-8">
                    {loading ? (
                        <div className="flex flex-col items-center justify-center py-8 space-y-4">
                            <span className="icon-loader text-4xl text-[var(--primary)] animate-spin"></span>
                            <p className="text-gray-600 font-medium">Loading system...</p>
                        </div>
                    ) : !selectedUser ? (
                        <div className="space-y-4 animate-fade-in">
                            <h2 className="text-center text-gray-600 font-medium mb-6">Select User Account</h2>
                            {users.length === 0 ? (
                                <p className="text-center text-gray-500">No users available. Please contact your administrator.</p>
                            ) : (
                                <div className="grid grid-cols-1 gap-3 max-h-[300px] overflow-y-auto pr-1">
                                    {users.map(user => (
                                        <button
                                            key={user.id}
                                            onClick={() => handleUserSelect(user)}
                                            className="flex items-center gap-4 p-4 rounded-xl border border-gray-100 hover:border-[var(--primary)] hover:bg-emerald-50 transition-all group w-full text-left"
                                        >
                                            <div className="w-12 h-12 rounded-full bg-slate-100 flex items-center justify-center text-slate-500 font-bold shadow-sm">
                                                {user.name.split(' ').map(n => n[0]).join('').substring(0, 2)}
                                            </div>
                                            <div className="flex-1">
                                                <h3 className="font-bold text-gray-800 group-hover:text-[var(--primary)] transition-colors">{user.name}</h3>
                                                <p className="text-xs text-gray-500 capitalize">{user.role}</p>
                                            </div>
                                            <span className="icon-chevron-right text-gray-300 group-hover:text-[var(--primary)]"></span>
                                        </button>
                                    ))}
                                </div>
                            )}
                        </div>
                    ) : (
                        <form onSubmit={handleLogin} className="space-y-6 animate-fade-in">
                            <div className="text-center">
                                <div className="w-20 h-20 rounded-full bg-slate-200 flex items-center justify-center text-slate-500 font-bold text-2xl shadow-md mx-auto mb-3 border-4 border-white">
                                    {selectedUser.name.split(' ').map(n => n[0]).join('').substring(0, 2)}
                                </div>
                                <h2 className="text-xl font-bold text-gray-900">{selectedUser.name}</h2>
                                <p className="text-sm text-gray-500 capitalize">{selectedUser.role}</p>
                                <button
                                    type="button"
                                    onClick={() => setSelectedUser(null)}
                                    className="text-xs text-[var(--primary)] hover:underline mt-2"
                                >
                                    Switch User
                                </button>
                            </div>

                            <div className="relative">
                                <label className="block text-sm font-medium text-gray-700 mb-2">Enter Access PIN</label>
                                <input
                                    type="password"
                                    className="w-full text-center text-3xl tracking-widest py-3 border-b-2 border-gray-200 focus:border-[var(--primary)] outline-none transition-colors font-mono"
                                    maxLength="4"
                                    value={pin}
                                    autoFocus
                                    placeholder="••••"
                                    onChange={(e) => {
                                        setPin(e.target.value);
                                        setError('');
                                    }}
                                />
                                {error && <p className="text-red-500 text-xs mt-2 text-center flex items-center justify-center gap-1"><span className="icon-circle-alert"></span> {error}</p>}
                            </div>

                            <button
                                type="submit"
                                className="w-full bg-[var(--primary)] text-white py-3.5 rounded-xl font-bold hover:bg-[var(--primary-dark)] transition-transform active:scale-[0.98] shadow-lg shadow-emerald-200"
                            >
                                Login to Terminal
                            </button>

                    
                        </form>
                    )}
                </div>
                <div className="bg-gray-50 p-4 text-center border-t border-gray-100">
                    <p className="text-xs text-gray-400">© 2026 Pandan Labs</p>
                </div>
            </div>
        </div>
    );
}