import { useState } from 'react';
import { api } from '../../api.js';
import PasswordInput from '../../components/PasswordInput.jsx';

export default function CreateUserSection({ onCreated }) {
  const [form, setForm]       = useState({ email: '', password: '', displayName: '', role: 'user' });
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(null);
  const [err, setErr]         = useState(null);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true); setErr(null); setSuccess(null);
    try {
      const created = await api.post('/admin/users', {
        email:       form.email,
        password:    form.password,
        displayName: form.displayName || undefined,
        role:        form.role,
      });
      setSuccess(`Utilisateur "${created.display_name || created.email}" créé avec succès.`);
      setForm({ email: '', password: '', displayName: '', role: 'user' });
      onCreated?.();
    } catch (e) { setErr(e.message); }
    finally { setLoading(false); }
  };

  return (
    <div className="card">
      <h3 style={{ margin: '0 0 4px' }}>Créer un utilisateur</h3>
      <p className="text-muted" style={{ margin: '0 0 20px', fontSize: 'var(--fs-sm)' }}>
        Créez un nouveau compte manuellement sur la plateforme.
      </p>

      {success && <div className="success-msg" style={{ marginBottom: 16 }}>{success}</div>}
      {err     && <div className="error"       style={{ marginBottom: 16 }}>{err}</div>}

      <form onSubmit={handleSubmit} style={{ maxWidth: 480 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div>
            <label>Nom affiché</label>
            <input value={form.displayName} onChange={e => set('displayName', e.target.value)} placeholder="Prénom Nom" />
          </div>
          <div>
            <label>Email *</label>
            <input type="email" required value={form.email} onChange={e => set('email', e.target.value)} placeholder="utilisateur@exemple.com" />
          </div>
          <div>
            <label>Mot de passe *</label>
            <PasswordInput required minLength={8} value={form.password} onChange={e => set('password', e.target.value)} placeholder="8 caractères minimum" />
          </div>
          <div>
            <label>Rôle</label>
            <select value={form.role} onChange={e => set('role', e.target.value)}>
              <option value="user">Utilisateur</option>
              <option value="admin">Administrateur</option>
            </select>
          </div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 20 }}>
          <button type="submit" className="primary" disabled={loading}>
            {loading ? 'Création…' : 'Créer l\'utilisateur'}
          </button>
        </div>
      </form>
    </div>
  );
}
