import { Stack } from '@mui/material';
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { actionFullLogin } from '../api/api';
import LoginForm from '../components/LoginForm';
import Alert from '@mui/material/Alert';
import { useNavigate } from 'react-router-dom';
import Title from '../components/Title';

const LoginPage = () => {
  const token = useSelector(state => state.auth.token);
  const userId = useSelector(state => state.auth?.payload?.sub?.id);
  const error = useSelector(state => state.auth.error);
  const admin = useSelector(state => state.auth?.payload?.sub?.acl.includes('admin'));
  const dispatch = useDispatch();
  const navigate = useNavigate();

  useEffect(() => {
    if (token) {
      if (admin) {
        navigate('/admin');
      } else {
        navigate(`/user/${userId}`);
      }
    }
  }, [token]);

  const onLogin = (login, password) => {
    dispatch(actionFullLogin({ login, password }));
  }

  return (
    <>
      <Title>Login</Title>
      <Stack sx={{ maxWidth: '300px', width: '100%', m: '150px auto' }} spacing={2}>
        <LoginForm submit='Login' onSubmit={onLogin} />
        {error && <Alert severity="error">You entered wrong login or password!</Alert>}
      </Stack>
    </>
  )
}
export default LoginPage;