import { useEffect } from 'react';
import { useNavigate } from 'react-router';

import { Box, CircularProgress } from '@mui/material';

import { useAppDispatch } from '../store';
import { fetchProjectsList } from '../store/projectsSlice/thunks';

// Landing route: send the user to their first project, or to project creation
// when none exist yet. Mirrors the legacy projectsMainController.
export const ProjectsMain = () => {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();

  useEffect(() => {
    dispatch(fetchProjectsList({ limit: 1 }))
      .unwrap()
      .then(response => {
        const first = response.data?.[0];
        if (first) {
          localStorage.setItem('projectID', String(first.id));
          navigate(`/project/${first.id}`, { replace: true });
        } else {
          navigate('/project/create', { replace: true });
        }
      })
      .catch(() => navigate('/project/create', { replace: true }));
  }, [dispatch, navigate]);

  return (
    <Box sx={{ display: 'flex', justifyContent: 'center', mt: 8 }}>
      <CircularProgress />
    </Box>
  );
};
