import React, { useState } from 'react';
import axios from 'axios'; // Importar axios
import { useAuth } from '../contexts/AuthContext';
import type { LoginRequestDto } from '../models/dtos/Usuarios/LoginRequestDto'; // Usar type

// Importaciones de Material UI
import { Container, TextField, Button, Typography, Box, Alert } from '@mui/material';
import authService from '../services/Usuarios/authService';

import logo from '../assets/eldia.png';

const LoginPage: React.FC = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const { login } = useAuth();

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setError(null);
    setLoading(true);

    const loginData: LoginRequestDto = { Username: username, Password: password };

    try {
      const response = await authService.login(loginData);
      login(response);
    } catch (err: any) {
      console.error("Login error:", err);
      if (axios.isAxiosError(err) && err.response) {
        setError(err.response.data?.message || 'Error al iniciar sesión. Verifique sus credenciales.');
      } else {
        setError('Ocurrió un error inesperado.');
      }
      // Importante: NO llamar a navigate('/') aquí en el catch,
      // porque el estado isAuthenticated no habrá cambiado a true
    } finally {
      setLoading(false);
    }
  };

  return (
    <Container component="main" maxWidth="xs">
       {/* Contenedor responsive para la imagen */}
       <Box
          component="div"
          sx={{
            marginTop: 3,
            width: '100%',        // ocupa todo el ancho disponible
            maxWidth: 429,        // pero no más de 429px
            mx: 'auto',           // margin-left/right auto para centrar
          }}
        >
          <img
            src={logo}
            alt="Logo"
            style={{ width: '100%', height: 'auto', display: 'block' }}
          />
        </Box>
      <Box
        sx={{
          marginTop: 3,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
        }}
      >
        <Typography component="h1" variant="h5">
          Iniciar Sesión
        </Typography>
        <Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }}>
          <TextField
            margin="normal"
            required
            fullWidth
            id="username"
            label="Usuario"
            name="username"
            autoComplete="username"
            autoFocus
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            disabled={loading}
          />
          <TextField
            margin="normal"
            required
            fullWidth
            name="password"
            label="Contraseña"
            type="password"
            id="password"
            autoComplete="current-password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            disabled={loading}
          />
          {error && (
            <Alert severity="error" sx={{ mt: 2, width: '100%' }}>
              {error}
            </Alert>
          )}
          <Button
            type="submit"
            fullWidth
            variant="contained"
            sx={{ mt: 3, mb: 2 }}
            disabled={loading}
          >
            {loading ? 'Ingresando...' : 'Ingresar'}
          </Button>
        </Box>
      </Box>
    </Container>
  );
};

export default LoginPage;