import React, { useState } from 'react';
import { UserRole } from '../types';
import { createUser } from '../services/users';

interface UserManagementProps {
  isMaster: boolean;
}

export default function UserManagement({ isMaster }: UserManagementProps) {
  const [nome, setNome] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [role, setRole] = useState<UserRole>(UserRole.DILIGENCIADOR);
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  if (!isMaster) {
    return (
      <div className="p-6">
        <div className="bg-red-500/20 text-red-300 p-4 rounded">
          Apenas usuários Master podem cadastrar novos usuários.
        </div>
      </div>
    );
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setMessage(null);
    setLoading(true);
    try {
      await createUser({ nome, email, role, password });
      setMessage('Usuário cadastrado com sucesso.');
      setNome(''); setEmail(''); setPassword(''); setRole(UserRole.DILIGENCIADOR);
    } catch (err: any) {
      try {
        const msg = JSON.parse(err.message)?.error || 'Erro ao cadastrar usuário.';
        setError(msg);
      } catch {
        setError('Erro ao cadastrar usuário.');
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="p-6">
      <h2 className="text-xl font-bold text-primary-light mb-4">Cadastro de Usuários</h2>
      <form onSubmit={handleSubmit} className="space-y-4 max-w-xl">
        {message && <div className="text-green-300 text-sm">{message}</div>}
        {error && <div className="text-red-300 text-sm">{error}</div>}
        <div>
          <label className="block text-sm mb-1">Nome</label>
          <input
            type="text"
            value={nome}
            onChange={e => setNome(e.target.value)}
            className="w-full px-3 py-2 rounded bg-primary-dark border border-primary-medium text-white focus:outline-none"
            required
          />
        </div>
        <div>
          <label className="block text-sm mb-1">E-mail</label>
          <input
            type="email"
            value={email}
            onChange={e => setEmail(e.target.value)}
            className="w-full px-3 py-2 rounded bg-primary-dark border border-primary-medium text-white focus:outline-none"
            required
          />
        </div>
        <div>
          <label className="block text-sm mb-1">Senha</label>
          <input
            type="password"
            value={password}
            onChange={e => setPassword(e.target.value)}
            className="w-full px-3 py-2 rounded bg-primary-dark border border-primary-medium text-white focus:outline-none"
            required
          />
        </div>
        <div>
          <label className="block text-sm mb-1">Papel</label>
          <select
            value={role}
            onChange={e => setRole(e.target.value as UserRole)}
            className="w-full px-3 py-2 rounded bg-primary-dark border border-primary-medium text-white focus:outline-none"
          >
            {Object.values(UserRole).map(r => (
              <option key={r} value={r} className="bg-primary-dark">{r}</option>
            ))}
          </select>
        </div>
        <button
          type="submit"
          className="bg-primary-light text-primary-dark font-semibold px-6 py-2 rounded hover:bg-opacity-90 disabled:opacity-60"
          disabled={loading}
        >
          {loading ? 'Salvando...' : 'Cadastrar'}
        </button>
      </form>
    </div>
  );
}