'use client'

import * as React from 'react';
import { Box, Button, Typography, Avatar, Card, CardContent, CardActions, CardActionArea, CardMedia, Grid2, SpeedDial, SpeedDialAction } from '@mui/material';
import { Add, ContentCopy, Delete, Edit } from '@mui/icons-material';
import Image from 'next/image';
import EditDialog from '../gare/classique/EditDialog';
import { redirect } from 'next/navigation';


export default function LoginPage() {

    const [user, setUser] = React.useState({});
    const [gares, setGares] = React.useState([]);

    const [edit, setEdit] = React.useState(false);
    const [initialValues, setInitialValues] = React.useState({});
    const [editId, setEditId] = React.useState(null);

    React.useEffect(() => {
        async function getUser() {
            const res = await fetch('/api/auth/user', {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' },
            });

            if (res.status === 200) {
                setUser((await res.json()).user);
            } else if (!(await res.json()).isLogedIn) {
                redirect('/login');
            } else {
                alert('Erreur lors de la récupération de l\'utilisateur');
            }
        }

        getUser();
    }, []);

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

            if (res.status === 200) {
                setGares(await res.json());
            } else {
                alert('Erreur lors de la récupération des gares');
            }
        }

        getGares();
    }, []);

    const handleCard = (id, type) => {
        if (type === 'Classic') {
            window.location.href = `/creator/gare/classique/${id}`;
        } else if (type === 'RER') {
            window.location.href = `/creator/gare/rer/${id}`;
        } else if (type === 'AFL') {
            window.location.href = `/creator/gare/afl/${id}`;
        }
    }

    const handleNewBtn = (key) => {
        if (key === 'classic') {
            redirect('/creator/gare/classique/new');
        } else if (key === 'rer') {
            redirect('/creator/gare/rer/new');
        } else {
            redirect('/creator/gare/afl/new');
        }
    }

    const handleEdit = (gare) => {
        setInitialValues(gare);
        setEditId(gare.ID);
        setEdit(true);
    }

    const handleSubmitEdit = async (values) => {
        const res = await fetch('/api/gares?id=' + values.id, {
            method: 'PATCH',
            body: JSON.stringify(values),
            headers: { 'Content-Type': 'application/json' }
        });
        if (res.status === 200) {
            setEdit(false);
            window.location.reload();
        } else {
            alert('Erreur lors de la modification de la gare');
        }
    }

    return (
        <>
            <Box>
                <Box
                    sx={{
                        width: "100%",
                        height: "250px",
                        backgroundImage: "url('https://upload.wikimedia.org/wikipedia/commons/thumb/c/c0/Gare_de_Haguenau_R%C3%A9giolis.jpg/1280px-Gare_de_Haguenau_R%C3%A9giolis.jpg')",
                        backgroundSize: "cover",
                        backgroundPosition: "center",
                        position: "relative",
                    }}
                />
            </Box>
            <Box
                sx={{
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",
                    position: "relative",
                    top: "-75px", // Positionne l'avatar sur la bannière
                }}
            >
                <Avatar
                    alt="User Profile"
                    sx={{
                        width: "150px",
                        height: "150px",
                        border: "5px solid #171717",
                        boxShadow: "0 8px 8px rgba(0,0,0,0.1)",
                    }}
                />
            </Box>
            <Box alignItems='center' display='flex' flexDirection='column' sx={{ marginTop: '-50px' }}>
                <Typography variant='h4'>{user.USERNAME}</Typography>
                <Grid2 container spacing={4} sx={{ paddingTop: '15px' }}>
                    {gares.map(gare => (
                        <Grid2 xs={12} sm={6} md={4} lg={3} xl={2} key={gare.ID}>
                            <Card variant='outlined' sx={{ minWidth: 256 }}>
                                <CardActionArea onClick={(e) => handleCard(gare.ID, gare.TYPE)}>
                                    <CardMedia component='div' sx={{ height: 140, backgroundSize: 'auto 120px' }} image='/assets/images/SNCF.svg' />
                                    <CardContent>
                                        <Typography variant='h6'>{gare.NAME}</Typography>
                                    </CardContent>
                                </CardActionArea>
                                <CardActions>
                                    <Button variant='text' startIcon={<Edit />} onClick={(e) => handleEdit(gare)}>Modifier</Button>
                                    <Button variant='text' startIcon={<ContentCopy />}>Dupliquer</Button>
                                    <Button variant='text' startIcon={<Delete />}>Supprimer</Button>
                                </CardActions>
                            </Card>
                        </Grid2>
                    ))}
                </Grid2>
                <EditDialog show={edit} id={editId} values={initialValues} onClose={(e) => setEdit(false)} onSubmit={handleSubmitEdit} />
            </Box>
            <SpeedDial ariaLabel='Nouvelle gare' sx={{ position: 'fixed', bottom: 16, right: 16 }} icon={<Add />} >
                <SpeedDialAction key='classic' icon={<Image src='/assets/images/SNCF.svg' height={32} width={64} alt='SNCF Logo' />} tooltipTitle='Gare classique' onClick={(e) => handleNewBtn('classic')} />
                <SpeedDialAction key='rer' icon={<Image src='/assets/images/RATP.svg' height={32} width={32} alt='RER Logo' />} tooltipTitle='Gare RER' onClick={(e) => handleNewBtn('rer')} />
                <SpeedDialAction key='afl' icon={<Image src='/assets/images/AFL.svg' height={32} width={64} alt='AFL Logo' />} tooltipTitle='Gare AFL' onClick={(e) => handleNewBtn('afl')} />
            </SpeedDial>
        </>
    )

}