'use client';

import { ContentCopy, Delete, Edit } from '@mui/icons-material';
import { Typography, Box, Grid2, Card, CardContent, CardActionArea, CardActions, CardMedia, Button, Snackbar } from '@mui/material';
import Image from 'next/image';
import { usePathname } from 'next/navigation';
import EditDialog from '@/app/(general)/creator/gare/classique/EditDialog';
import * as React from 'react';

export default function GareClassique() {
    const router = usePathname();
    const id = router.split('/').pop();

    const [trains, setTrains] = React.useState([]);
    const [show, setShow] = React.useState(false);
    const [snackbar, setSnackbar] = React.useState(false);

    const [name, setName] = React.useState('');
    const [values, setValues] = React.useState({});

    React.useEffect(() => {
        async function getGare() {
            const res = await fetch('/api/gares?id=' + id, {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' },
            });

            if (res.status === 200) {
                const data = await res.json();
                setName(data.NAME);
                setValues(data);
            } else {
                alert('Erreur lors de la récupération de la gare');
            }
        }

        getGare();
    }, []);

    React.useEffect(() => {
        async function getTrains() {
            const res = await fetch('/api/trains?gare_id=' + id, {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' },
            });

            if (res.status === 200) {
                setTrains(await res.json());
            } else {
                if (res.status === 410) {
                    setSnackbar(true);
                } else {
                    alert('Erreur lors de la récupération des trains');
                }
            }
        }

        getTrains();
    }, []);

    const handleCard = (e) => {

    }

    const handleEdit = (e) => {
        setShow(true);
    }

    const handleEditSubmit = async (data) => {
        if (!name) {
            return;
        }

        const req = await fetch('/api/gares?id=' + id, {
            method: 'PATCH',
            body: JSON.stringify({ name: data.name, infos: data.infos, infos_type: data.infosType, shared: data.shared }),
            headers: { 'Content-Type': 'application/json' },
        });

        if (req.status == 200) {
            setShow(false);
            window.location.reload();
        } else {
            alert('Erreur lors de la mise à jour de la gare');
        }
    }

    return (
        <>
            <Box alignItems='center' display='flex' flexDirection='column' marginTop='20px'>
                <Image src='/assets/images/SNCF.svg' alt="Gare classique" width={128} height={128} />
                <Button variant='text' endIcon={<Edit />} sx={{ marginTop: '20px' }} onClick={handleEdit}><Typography variant="h4">{name}</Typography></Button>
                <Grid2 container spacing={4} sx={{ paddingTop: '15px' }}>
                    {trains.map((train) => (
                        <Grid2 key={train.ID}>
                            <Card variant='outlined' sx={{ minWidth: '256px' }}>
                                <CardActionArea onClick={(e) => handleCard(e)}>
                                    <CardMedia component='div' sx={{ height: 140, backgroundSize: 'auto 120px' }} image='/assets/images/SNCF.svg' />
                                    <CardContent>
                                        <Typography variant='h6'>{train.DESTINATION}</Typography>
                                        <Typography variant='h7'>{train.NUMBER}</Typography>
                                    </CardContent>
                                </CardActionArea>
                                <CardActions>
                                    <Button variant='text' startIcon={<Edit />}>Modifier</Button>
                                    <Button variant='text' startIcon={<ContentCopy />}>Dupliquer</Button>
                                    <Button variant='text' startIcon={<Delete />}>Supprimer</Button>
                                </CardActions>
                            </Card>
                        </Grid2>
                    ))}
                </Grid2>
            </Box>
            <Snackbar open={snackbar} message="Il n'y a aucun train dans cette gare !"/>
            <EditDialog show={show} values={values} onClose={(e) => setShow(false)} onSubmit={handleEditSubmit} />
        </>
    );
}