import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '../../stores/authStore';
import { Button } from '../ui/Button';
import { Input } from '../ui/Input';
import { Mail, Lock, LogIn } from 'lucide-react';

export function LoginForm() {
  const navigate = useNavigate();
  const { login, isLoading, error, clearError } = useAuthStore();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [validationError, setValidationError] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    clearError();
    setValidationError('');

    if (!email || !password) {
      setValidationError('Por favor, completa todos los campos');
      return;
    }

    try {
      // Determinar si es email o username
      const isEmail = email.includes('@');
      if (isEmail) {
        await login({ email, password });
      } else {
        await login({ username: email, password });
      }
      navigate('/');
    } catch {
      // Error handled by store
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {(error || validationError) && (
        <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-600">
          {error || validationError}
        </div>
      )}

      <Input
        type="text"
        label="Usuario o correo electrónico"
        placeholder="usuario o tu@email.com"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        icon={<Mail className="w-5 h-5 text-gray-400" />}
        autoComplete="username"
      />

      <Input
        type="password"
        label="Contraseña"
        placeholder="••••••••"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        icon={<Lock className="w-5 h-5 text-gray-400" />}
        autoComplete="current-password"
      />

      <Button type="submit" className="w-full" isLoading={isLoading}>
        <LogIn className="w-5 h-5 mr-2" />
        Iniciar sesión
      </Button>
    </form>
  );
}
