import React, { useState } from 'react';
import logo from '../../assets/logo.png';
// We'll define some inline styles or simple CSS for the login page

const Login = ({ onLogin, users }) => {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [selectedRole, setSelectedRole] = useState('User'); // 'User' or 'Admin'
    const [error, setError] = useState('');

    const handleLogin = (e) => {
        e.preventDefault();
        setError(''); // Clear previous errors

        // Find user by username OR email (case insensitive)
        const foundUser = users.find(u =>
            u.username.toLowerCase() === username.toLowerCase() ||
            (u.email && u.email.toLowerCase() === username.toLowerCase())
        );

        if (foundUser) {
            // 1. Role Check: Ensure the user trying to login matches the selected role tab
            // Admins have 'Admin' or 'System Admin' role. Users have 'User', 'Technician', etc.
            const isAdminRole = foundUser.role === 'Admin' || foundUser.role === 'System Admin';

            if (selectedRole === 'Admin' && !isAdminRole) {
                setError('Access Denied. This account is not an Administrator.');
                return;
            }
            if (selectedRole === 'User' && isAdminRole) {
                // Optional: Allow admins to login as users, or restrict? 
                // Usually fine, but let's be strict for clarity based on user request "path"
                // "make path... user or admin". Let's assume strict paths.
                // Actually, admins often use user features. But let's stick to the prompt's implication of separation.
                // For now, if an admin tries to log in via the 'User' tab, we'll allow it, but the system will treat them as a user.
                // If strict separation is needed, uncomment the line below:
                // setError('Access Denied. This account is an Administrator. Please use the Admin tab.'); return;
            }

            // 2. Password Check
            // Legacy/Default logic + New logic
            // If user has a specific password property (newly added), check that.
            // Else fallback to defaults.
            const isValidPassword =
                (foundUser.password && foundUser.password === password) || // New users with explicit password
                (!foundUser.password && ( // Legacy mock users without explicit password property
                    (foundUser.username === 'admin' && password === 'admin') ||
                    (foundUser.username === 'user' && password === 'user') ||
                    (foundUser.username !== 'admin' && foundUser.username !== 'user' && (password === foundUser.username || password === '123'))
                ));

            if (isValidPassword) {
                onLogin(foundUser);
            } else {
                setError('Invalid password.');
            }
        } else {
            setError('User not found.');
        }
    };

    return (
        <div style={{
            height: '100vh',
            width: '100vw',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: '#0f172a', // Dark background matching theme
            color: 'white'
        }}>
            <div style={{
                width: '100%',
                maxWidth: '400px',
                padding: '2rem',
                backgroundColor: '#1e293b',
                borderRadius: '12px',
                boxShadow: '0 10px 25px -5px rgba(0, 0, 0, 0.5), 0 8px 10px -6px rgba(0, 0, 0, 0.1)',
                border: '1px solid #334155'
            }}>
                <div style={{ textAlign: 'center', marginBottom: '2rem' }}>
                    <img src={logo} alt="Weststar" style={{ maxWidth: '180px', marginBottom: '1rem' }} />
                    <h2 style={{ fontSize: '1.5rem', fontWeight: 'bold', color: '#f8fafc' }}>Sign In</h2>
                    <p style={{ color: '#94a3b8' }}>MRO Aviation System</p>
                </div>

                <div style={{ display: 'flex', marginBottom: '1.5rem', borderBottom: '1px solid #334155' }}>
                    <button
                        onClick={() => { setSelectedRole('User'); setError(''); }}
                        style={{
                            flex: 1,
                            padding: '0.75rem',
                            background: 'none',
                            border: 'none',
                            borderBottom: selectedRole === 'User' ? '2px solid #2563eb' : '2px solid transparent',
                            color: selectedRole === 'User' ? 'white' : '#94a3b8',
                            fontWeight: selectedRole === 'User' ? '600' : '400',
                            cursor: 'pointer',
                            fontSize: '1rem'
                        }}
                    >
                        User Login
                    </button>
                    <button
                        onClick={() => { setSelectedRole('Admin'); setError(''); }}
                        style={{
                            flex: 1,
                            padding: '0.75rem',
                            background: 'none',
                            border: 'none',
                            borderBottom: selectedRole === 'Admin' ? '2px solid #2563eb' : '2px solid transparent',
                            color: selectedRole === 'Admin' ? 'white' : '#94a3b8',
                            fontWeight: selectedRole === 'Admin' ? '600' : '400',
                            cursor: 'pointer',
                            fontSize: '1rem'
                        }}
                    >
                        Admin Login
                    </button>
                </div>

                <form onSubmit={handleLogin} style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
                    {error && (
                        <div style={{
                            padding: '0.75rem',
                            backgroundColor: 'rgba(239, 68, 68, 0.1)',
                            color: '#ef4444',
                            borderRadius: '6px',
                            fontSize: '0.875rem',
                            textAlign: 'center'
                        }}>
                            {error}
                        </div>
                    )}

                    <div>
                        <label style={{ display: 'block', fontSize: '0.875rem', marginBottom: '0.5rem', color: '#cbd5e1' }}>Username or Email</label>
                        <input
                            type="text"
                            value={username}
                            onChange={(e) => setUsername(e.target.value)}
                            style={{
                                width: '100%',
                                padding: '0.75rem',
                                borderRadius: '6px',
                                border: '1px solid #334155',
                                backgroundColor: '#0f172a',
                                color: 'white',
                                outline: 'none'
                            }}
                            placeholder="Enter username or email"
                        />
                    </div>

                    <div>
                        <label style={{ display: 'block', fontSize: '0.875rem', marginBottom: '0.5rem', color: '#cbd5e1' }}>Password</label>
                        <input
                            type="password"
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                            style={{
                                width: '100%',
                                padding: '0.75rem',
                                borderRadius: '6px',
                                border: '1px solid #334155',
                                backgroundColor: '#0f172a',
                                color: 'white',
                                outline: 'none'
                            }}
                            placeholder="Enter your password"
                        />
                    </div>

                    <button
                        type="submit"
                        style={{
                            padding: '0.75rem',
                            backgroundColor: '#2563eb', // Blue accent
                            color: 'white',
                            border: 'none',
                            borderRadius: '6px',
                            fontWeight: '600',
                            cursor: 'pointer',
                            marginTop: '1rem',
                            transition: 'background-color 0.2s'
                        }}
                    >
                        Sign In
                    </button>
                </form>

                <div style={{ marginTop: '1.5rem', textAlign: 'center', fontSize: '0.8rem', color: '#64748b' }}>
                    Standard: <strong>admin/admin</strong> or <strong>user/user</strong>.<br />
                    New Users: Password is same as username or "123".
                </div>
            </div>
        </div>
    );
};

export default Login;
