import { useEffect, useState } from 'react';
import { api } from '../api.js';

export default function UsersAdmin({ currentUser }) {
  const [users, setUsers] = useState([]);
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [role, setRole] = useState('user');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(true);

  async function load() {
    setLoading(true);
    try {
      const data = await api('/users');
      setUsers(data.users);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

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

  async function createUser(e) {
    e.preventDefault();
    setError('');
    try {
      await api('/users', { method: 'POST', body: { email, password, role } });
      setEmail('');
      setPassword('');
      setRole('user');
      await load();
    } catch (err) {
      setError(err.message);
    }
  }

  async function removeUser(id) {
    if (!confirm('Удалить пользователя? Все его данные будут стёрты.')) return;
    setError('');
    try {
      await api(`/users/${id}`, { method: 'DELETE' });
      await load();
    } catch (err) {
      setError(err.message);
    }
  }

  return (
    <div className="stack">
      <div className="card">
        <h2>Создать пользователя</h2>
        <form className="row-form" onSubmit={createUser}>
          <input placeholder="email" value={email} onChange={(e) => setEmail(e.target.value)} />
          <input placeholder="пароль (мин. 6)" type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
          <select value={role} onChange={(e) => setRole(e.target.value)}>
            <option value="user">Пользователь</option>
            <option value="admin">Администратор</option>
          </select>
          <button type="submit">Добавить</button>
        </form>
        {error && <div className="error">{error}</div>}
      </div>

      <div className="card">
        <h2>Пользователи</h2>
        {loading ? (
          <p className="muted">Загрузка…</p>
        ) : (
          <table className="table">
            <thead>
              <tr><th>Email</th><th>Роль</th><th>Создан</th><th></th></tr>
            </thead>
            <tbody>
              {users.map((u) => (
                <tr key={u.id}>
                  <td>{u.email}</td>
                  <td>{u.role === 'admin' ? 'Администратор' : 'Пользователь'}</td>
                  <td className="muted">{u.created_at}</td>
                  <td>
                    {u.id !== currentUser.id && (
                      <button className="danger" onClick={() => removeUser(u.id)}>Удалить</button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
