import React, { useState, useEffect, useCallback } from 'react';
import axios from 'axios';

const s = {
  overlay: {
    position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.75)',
    display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 2500,
  },
  modal: {
    width: '560px', maxWidth: '95vw', maxHeight: '90vh', background: '#111217',
    borderRadius: '12px', boxShadow: '0 16px 40px rgba(0,0,0,0.8)', color: '#f8f9fa',
    overflow: 'hidden', border: '1px solid #2a2b3a', display: 'flex', flexDirection: 'column',
  },
  header: {
    padding: '18px 24px', borderBottom: '1px solid #222',
    background: 'linear-gradient(135deg, #000000, #151622)',
    display: 'flex', justifyContent: 'space-between', alignItems: 'center',
  },
  title: { fontSize: '18px', fontWeight: 700 },
  close: { background: 'none', border: 'none', color: '#9ca0b8', fontSize: '22px', cursor: 'pointer', lineHeight: 1 },
  body: { padding: '18px 24px', overflowY: 'auto' },
  error: {
    background: '#3a1414', borderRadius: '6px', padding: '9px 11px',
    fontSize: '12px', color: '#ff9b9b', border: '1px solid #c0392b', marginBottom: '14px',
  },
  table: { width: '100%', borderCollapse: 'collapse', marginBottom: '20px', fontSize: '13px' },
  th: { textAlign: 'left', padding: '8px 10px', color: '#9ca0b8', borderBottom: '1px solid #222', fontWeight: 600 },
  td: { padding: '8px 10px', borderBottom: '1px solid #1a1b22' },
  roleBadge: (admin) => ({
    fontSize: '11px', fontWeight: 700, padding: '2px 8px', borderRadius: '10px',
    background: admin ? '#3b2e00' : '#1a2733', color: admin ? '#ffd666' : '#7fc4ff',
    border: `1px solid ${admin ? '#d4af37' : '#2a4a66'}`,
  }),
  smallBtn: {
    padding: '4px 10px', borderRadius: '5px', border: '1px solid #333544',
    background: '#050608', color: '#f8f9fa', fontSize: '12px', cursor: 'pointer', marginRight: '6px',
  },
  dangerBtn: {
    padding: '4px 10px', borderRadius: '5px', border: '1px solid #5a2020',
    background: '#2a1010', color: '#ff9b9b', fontSize: '12px', cursor: 'pointer',
  },
  sectionTitle: { fontSize: '14px', fontWeight: 700, margin: '6px 0 12px 0', color: '#e5e7f1' },
  row: { display: 'flex', gap: '10px', flexWrap: 'wrap', alignItems: 'flex-end' },
  field: { flex: '1 1 140px' },
  label: { fontSize: '12px', fontWeight: 600, marginBottom: '4px', color: '#e5e7f1' },
  input: {
    width: '100%', padding: '8px 10px', borderRadius: '6px',
    border: '1px solid #333544', background: '#050608', color: '#f8f9fa',
    fontSize: '13px', fontFamily: 'inherit', boxSizing: 'border-box',
  },
  addBtn: {
    padding: '9px 18px', borderRadius: '6px', border: 'none',
    background: 'linear-gradient(135deg, #d4af37 0%, #ffdf8a 100%)',
    color: '#000', fontWeight: 700, fontSize: '13px', cursor: 'pointer',
  },
};

export default function UserManagementModal({ currentUser, onClose }) {
  const [users,    setUsers]    = useState([]);
  const [error,    setError]    = useState('');
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [role,     setRole]     = useState('user');

  const load = useCallback(async () => {
    try {
      const { data } = await axios.get('/api/users');
      setUsers(data);
    } catch (err) {
      setError(err.response?.data?.error || 'Failed to load users');
    }
  }, []);

  useEffect(() => { load(); }, [load]);

  const addUser = async (e) => {
    e.preventDefault();
    setError('');
    try {
      await axios.post('/api/users', { username, password, role });
      setUsername(''); setPassword(''); setRole('user');
      load();
    } catch (err) {
      setError(err.response?.data?.error || 'Failed to create user');
    }
  };

  const removeUser = async (u) => {
    if (!window.confirm(`Delete user "${u.username}"? They will lose access immediately.`)) return;
    setError('');
    try {
      await axios.delete(`/api/users/${u.id}`);
      load();
    } catch (err) {
      setError(err.response?.data?.error || 'Failed to delete user');
    }
  };

  const resetPassword = async (u) => {
    const pw = window.prompt(`Enter a new password for "${u.username}" (min 6 characters):`);
    if (pw == null) return;
    setError('');
    try {
      await axios.patch(`/api/users/${u.id}/password`, { password: pw });
      window.alert('Password updated.');
    } catch (err) {
      setError(err.response?.data?.error || 'Failed to update password');
    }
  };

  return (
    <div style={s.overlay} onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div style={s.modal} onClick={(e) => e.stopPropagation()}>
        <div style={s.header}>
          <div style={s.title}>User Management</div>
          <button style={s.close} onClick={onClose} title="Close">×</button>
        </div>

        <div style={s.body}>
          {error && <div style={s.error}>{error}</div>}

          <table style={s.table}>
            <thead>
              <tr>
                <th style={s.th}>Username</th>
                <th style={s.th}>Role</th>
                <th style={s.th}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {users.map((u) => (
                <tr key={u.id}>
                  <td style={s.td}>
                    {u.username}{u.id === currentUser?.id && <span style={{ color: '#9ca0b8' }}> (you)</span>}
                  </td>
                  <td style={s.td}><span style={s.roleBadge(u.role === 'admin')}>{u.role}</span></td>
                  <td style={s.td}>
                    <button style={s.smallBtn} onClick={() => resetPassword(u)}>Reset Password</button>
                    {u.id !== currentUser?.id && (
                      <button style={s.dangerBtn} onClick={() => removeUser(u)}>Delete</button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

          <div style={s.sectionTitle}>Add New User</div>
          <form style={s.row} onSubmit={addUser}>
            <div style={s.field}>
              <div style={s.label}>Username</div>
              <input style={s.input} value={username} onChange={(e) => setUsername(e.target.value)} required />
            </div>
            <div style={s.field}>
              <div style={s.label}>Password</div>
              <input style={s.input} type="password" value={password} onChange={(e) => setPassword(e.target.value)} required />
            </div>
            <div style={{ ...s.field, flex: '0 0 110px' }}>
              <div style={s.label}>Role</div>
              <select style={s.input} value={role} onChange={(e) => setRole(e.target.value)}>
                <option value="user">User</option>
                <option value="admin">Admin</option>
              </select>
            </div>
            <button style={s.addBtn} type="submit">Add User</button>
          </form>
        </div>
      </div>
    </div>
  );
}
