import axios from 'axios';
import { useState } from 'react';
import { envConfig } from '../envConfigurations/EnvConfigurations';
import './Impressions.css';

export const Login = () => {
    const [user, setUser] = useState('');
    const [password, setPassword] = useState('');
    const [message, setMessage] = useState('');
    
    const handleLogin = async () => {
        const url = envConfig().apiUrl;
        setMessage('')

        try {
            const response = await axios.post(`${url}/login`, {
                user,
                password,
            });

            if (response.data?.token) {
                localStorage.setItem('token', response.data.token);
                localStorage.setItem('session', user);
                setMessage('Inicio de sesión exitoso');
                window.location.href = '/';
            } else {
                setMessage('Credenciales incorrectas');
            }
        } catch (error) {
            const errorMessage = error.response?.data?.error || 'Error de conexión con la base de datos';

            setMessage(errorMessage);
        }
    };

    return (
        <section className='containerLogin'>

            <form
                className='login'
                onSubmit={(e) => {
                    e.preventDefault();
                    handleLogin();
                }}
            >
                <h2 className='textHeader'>Inicio de sesión</h2>

                <div className='containerInput'>
                    <label className='label'>Usuario</label>
                    <input
                        type='text'
                        value={user}
                        onChange={(e) => setUser(e.target.value)}
                        placeholder='Coloca tu usuario...'
                    />
                </div>

                <div className='containerInput relative'>
                    <label className='label'>Contraseña</label>
                    <input
                        type={'password'}
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        placeholder='Coloca tu contraseña...'
                    />
                </div>

                <button
                    className='button button-search'
                    style={{ maxWidth: '100%', width: '100%' }}
                    type='submit'
                >Iniciar sesión
                </button>
            </form>
            {message &&
                <div
                    className={`messageBox ${message.includes('exitoso') ? 'success' : 'error'}`}
                    style={{ marginTop: '10px' }}
                >
                    {message}
                </div>
            }
        </section>
    );
};
//IO