import React, { useEffect } from 'react';
import { Box, Typography, Container, CircularProgress } from '@mui/material';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';

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

    useEffect(() => {
        const handleCreate = async () => {
            try {
                const apiUrl = window.runtimeConfig?.API_URL || 'http://localhost:8000';
                const httpApiUrl = apiUrl.replace(/^ws/, 'http');
                const response = await axios.post(`${httpApiUrl}/sessions`);
                const { sessionId } = response.data;
                navigate(`/session/${sessionId}`);
            } catch (error) {
                console.error('Error creating session:', error);
            }
        };

        handleCreate();
    }, [navigate]);

    return (
        <Container maxWidth="sm">
            <Box
                sx={{
                    marginTop: 8,
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                }}
            >
                <CircularProgress />
                <Typography component="h1" variant="h6" sx={{ mt: 2 }}>
                    Creating a new session...
                </Typography>
            </Box>
        </Container>
    );
};

export default CreateSession;
