import React, { useState } from 'react';
import WidgetContainer from './WidgetContainer';
import styles from './WidgetStyles.module.css';

const MOCK_USERS = [
    { id: 'U-001', name: 'Admin User', role: 'System Admin', status: 'Active', email: 'admin@weststar.com' },
    { id: 'U-002', name: 'Kumar A/L Raju', role: 'Licensed Engineer', status: 'Active', email: 'kumar@weststar.com' },
    { id: 'U-003', name: 'Siti Aminah', role: 'Technical Records', status: 'Active', email: 'siti@weststar.com' },
    { id: 'U-004', name: 'Lee Chong Wei', role: 'Technician', status: 'On Leave', email: 'lee@weststar.com' },
];

const UserManagementWidget = ({ onExpand, users, onAddUser, onDeleteUser }) => {
    // const [users, setUsers] = useState(MOCK_USERS); // Moved to App.jsx
    const [isAdding, setIsAdding] = useState(false);
    // Added password field to state
    const [newUser, setNewUser] = useState({ name: '', role: 'Technician', email: '', password: '' });
    const [validationError, setValidationError] = useState('');

    const handleAdd = () => {
        setIsAdding(true);
        setValidationError('');
    };

    const saveUser = () => {
        // Validation
        if (!newUser.name || !newUser.email || !newUser.password) {
            setValidationError('All fields are required.');
            return;
        }
        if (!newUser.email.includes('@')) {
            setValidationError('Email must contain "@".');
            return;
        }
        if (newUser.password.length < 8) {
            setValidationError('Password must be at least 8 characters.');
            return;
        }

        onAddUser(newUser);
        setNewUser({ name: '', role: 'Technician', email: '', password: '' });
        setIsAdding(false);
        setValidationError('');
    };

    return (
        <WidgetContainer
            title="User Management"
            onAdd={handleAdd}
            onExpand={onExpand}
        >
            {isAdding && (
                <div className={styles.addItemForm}>
                    {validationError && (
                        <div style={{ color: '#ef4444', fontSize: '0.8rem', marginBottom: '0.5rem', padding: '0.5rem', background: 'rgba(239, 68, 68, 0.1)', borderRadius: '4px' }}>
                            {validationError}
                        </div>
                    )}
                    <input
                        placeholder="Full Name"
                        value={newUser.name}
                        onChange={e => setNewUser({ ...newUser, name: e.target.value })}
                        style={{ marginBottom: '0.5rem', width: '100%', padding: '0.5rem', borderRadius: '4px', background: 'var(--bg-primary)', border: '1px solid var(--border-color)', color: 'white' }}
                    />
                    <input
                        placeholder="Email (must contain @)"
                        value={newUser.email}
                        onChange={e => setNewUser({ ...newUser, email: e.target.value })}
                        style={{ marginBottom: '0.5rem', width: '100%', padding: '0.5rem', borderRadius: '4px', background: 'var(--bg-primary)', border: '1px solid var(--border-color)', color: 'white' }}
                    />
                    <input
                        type="password"
                        placeholder="Password (min 8 chars)"
                        value={newUser.password}
                        onChange={e => setNewUser({ ...newUser, password: e.target.value })}
                        style={{ marginBottom: '0.5rem', width: '100%', padding: '0.5rem', borderRadius: '4px', background: 'var(--bg-primary)', border: '1px solid var(--border-color)', color: 'white' }}
                    />
                    <select
                        value={newUser.role}
                        onChange={e => setNewUser({ ...newUser, role: e.target.value })}
                        style={{ marginBottom: '0.5rem', width: '100%', padding: '0.5rem', borderRadius: '4px', background: 'var(--bg-primary)', border: '1px solid var(--border-color)', color: 'white' }}
                    >
                        <option value="Technician">Technician</option>
                        <option value="Licensed Engineer">Licensed Engineer</option>
                        <option value="Technical Records">Technical Records</option>
                        <option value="System Admin">System Admin</option>
                    </select>
                    <div className={styles.formActions}>
                        <button onClick={saveUser} className={styles.saveBtn}>Save User</button>
                        <button onClick={() => setIsAdding(false)} className={styles.cancelBtn}>Cancel</button>
                    </div>
                </div>
            )}

            <div className={styles.list}>
                {users.map(user => (
                    <div key={user.id} className={styles.listItem} style={{
                        display: 'flex',
                        alignItems: 'center',
                        gap: '1rem',
                        padding: '1rem',
                        backgroundColor: 'rgba(255,255,255,0.03)',
                        borderRadius: '8px',
                        marginBottom: '0.75rem',
                        border: '1px solid rgba(255,255,255,0.05)'
                    }}>
                        {/* Avatar Placeholder */}
                        <div style={{
                            width: '40px',
                            height: '40px',
                            borderRadius: '50%',
                            backgroundColor: 'var(--bg-tertiary)',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            fontWeight: 'bold',
                            color: 'var(--accent-primary)',
                            border: '1px solid var(--border-color)'
                        }}>
                            {user.name.split(' ').map(n => n[0]).join('').substring(0, 2).toUpperCase()}
                        </div>

                        {/* Info */}
                        <div style={{ flex: 1 }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                                <span style={{ fontWeight: 600, color: 'var(--text-primary)' }}>{user.name}</span>
                                <span style={{
                                    fontSize: '0.7rem',
                                    padding: '0.1rem 0.5rem',
                                    borderRadius: '10px',
                                    backgroundColor: user.status === 'Active' ? 'rgba(34, 197, 94, 0.15)' : 'rgba(234, 179, 8, 0.15)',
                                    color: user.status === 'Active' ? '#4ade80' : '#fbbf24'
                                }}>
                                    {user.status}
                                </span>
                            </div>
                            <div style={{ fontSize: '0.85rem', color: 'var(--text-secondary)' }}>
                                {user.role} • {user.email}
                            </div>
                        </div>

                        <button
                            onClick={() => onDeleteUser(user.id)}
                            className={styles.deleteBtn}
                            title="Remove User"
                            style={{ opacity: 0.6 }}
                        >
                            🗑️
                        </button>
                    </div>
                ))}
            </div>
        </WidgetContainer>
    );
};

export default UserManagementWidget;
