import React, { useState } from 'react';
import { User, UserRole } from '../types';
import { request } from '../services/http';

interface LoginProps {
  onLoggedIn: (payload: { token: string; user: User }) => void;
}

export default function Login({ onLoggedIn }: LoginProps) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      const res = await request('/api/auth/login', {
        method: 'POST',
        body: JSON.stringify({ email, password }),
      });
      const { token, user } = res as { token: string; user: { id: string; nome: string; email: string; role: string } };
      const normalizedUser: User = { id: user.id, nome: user.nome, role: user.role as UserRole };
      localStorage.setItem('auth_token', token);
      localStorage.setItem('currentUserId', user.id);
      localStorage.setItem('currentUser', JSON.stringify(normalizedUser));
      onLoggedIn({ token, user: normalizedUser });
    } catch (err: any) {
      try {
        const msg = JSON.parse(err.message)?.error || 'Falha no login.';
        setError(msg);
      } catch {
        setError('Falha no login. Verifique suas credenciais.');
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-primary-dark text-white flex items-center justify-center">
      <form onSubmit={handleSubmit} className="bg-primary-medium/20 p-8 rounded-xl w-full max-w-md space-y-4">
        <h1 className="text-2xl font-bold text-primary-light text-center">Entrar</h1>
        {error && <div className="text-red-400 text-sm">{error}</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>
        <button
          type="submit"
          className="w-full bg-primary-light text-primary-dark font-semibold px-4 py-2 rounded hover:bg-opacity-90 disabled:opacity-60"
          disabled={loading}
        >
          {loading ? 'Entrando...' : 'Entrar'}
        </button>
      </form>
    </div>
  );
}