import { useNavigate } from 'react-router-dom';
import Login from '../../components/TopLevel/Login/Index';
import { login, createUser, getSeatSelectionCountApi } from '../../lib/api';
import { setItem } from '../../lib/localStorage';

const LoginPage = () => {
  const navigate = useNavigate();

  const onSubmit = async (email) => {
    const userData = await login(email);
    const fetchSeatSelectionCount = async (id) => {
      const data = await getSeatSelectionCountApi(id);
      if (data.selectionCount) {
        setItem('modal', false);
      } else {
        setItem('modal', true);
      }
      navigate('/');
    };
    if (userData) {
      setItem('user', userData.id);
      fetchSeatSelectionCount(userData?.id);
    } else {
      const data = await createUser(email);
      setItem('user', data.id);
      fetchSeatSelectionCount(data?.id);
    }
  };

  return <Login onSubmit={onSubmit} />;
};

export default LoginPage;
