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

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

  const onSubmit = async (email) => {
    try {
      const userData = await login(email);

      const fetchSeatSelectionCount = async (id) => {
        try {
          const data = await getSelectedSeatsApi();
          const currentData = data?.find((e) => e.userid == id);

          if (currentData?.selected?.length > 0) {
            setItem('modal', false);
          } else {
            setItem('modal', true);
          }

          navigate('/');
        } catch (error) {
          console.error('Error fetching seat selection count:', error);
        }
      };

      if (userData) {
        setItem('user', userData.id);
        fetchSeatSelectionCount(userData?.id);
      } else {
        const data = await createUser(email);
        setItem('user', data.id);
        fetchSeatSelectionCount(data?.id);
      }
    } catch (error) {
      console.error('Error during login or user creation:', error);
    }
  };

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

export default LoginPage;
