import { useState } from 'react';
import api from '../services/api';
import { useNavigate } from 'react-router-dom';
import { Monitor } from 'lucide-react';

export default function LoginPage() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const navigate = useNavigate();

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const res = await api.post('/auth/login', { username, password });
      localStorage.setItem('token', res.data.token);

      // CAMBIO AQUÍ: Guardar como objeto stringificado
      localStorage.setItem('user', JSON.stringify({ username }));

      navigate('/');
    } catch {
      alert('Credenciales inválidas');
    }
  };

  return (
    <div className="h-screen bg-slate-900 flex items-center justify-center">
      <div className="bg-white p-8 rounded-lg shadow-2xl w-96">
        <div className="flex justify-center mb-4 text-slate-800">
          <Monitor size={48} />
        </div>
        <h2 className="text-2xl font-bold text-center mb-6 text-slate-800">Acceso Mostrador</h2>
        <form onSubmit={handleLogin} className="space-y-4">
          <div>
            <label className="block text-sm font-bold mb-1">Usuario</label>
            <input type="text" value={username} onChange={e => setUsername(e.target.value)} className="w-full border p-2 rounded" autoFocus />
          </div>
          <div>
            <label className="block text-sm font-bold mb-1">Contraseña</label>
            <input type="password" value={password} onChange={e => setPassword(e.target.value)} className="w-full border p-2 rounded" />
          </div>
          <button type="submit" className="w-full bg-blue-600 text-white py-2 rounded font-bold hover:bg-blue-700">INGRESAR</button>
        </form>
      </div>
    </div>
  );
}