'use client'

import * as React from 'react';
import { Box, Button, TextField, Typography, Stepper, Step, StepLabel, StepButton, ButtonGroup, Autocomplete, FormControlLabel, FormLabel, RadioGroup, Radio, Checkbox, FormGroup, Snackbar } from '@mui/material';
import { Check, NavigateBefore, NavigateNext } from '@mui/icons-material';
import { redirect } from 'next/navigation';

export default function NewGareStep1Page() {

    const [name, setName] = React.useState('');
    const [folder, setFolder] = React.useState('default');
    const [texteInfos, setTexteInfos] = React.useState('');
    const [typeInfos, setTypeInfos] = React.useState('infos_normal');
    const [partage, setPartage] = React.useState(false);
    const [copie, setCopie] = React.useState(false);

    const [folders, setFolders] = React.useState([]);

    const [activeStep, setActiveStep] = React.useState(0);
    const [completed1, setCompleted1] = React.useState(false);
    const [completed2, setCompleted2] = React.useState(false);
    const [completed3, setCompleted3] = React.useState(false);
    const [copieDisabled, setCopieDisabled] = React.useState(true);

    const [snackOpen, setSnackOpen] = React.useState(false);

    const step1 = React.createRef();
    const step2 = React.createRef();
    const step3 = React.createRef();

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

            if (res.status === 200) {
                const fd = [];
                (await res.json()).forEach((f) => {
                    fd.push({ label: f.FOLDER });
                });
                setFolders(fd);
            } else {
                alert('Erreur lors de la récupération des dossiers');
            }
        }

        getFolders();
    }, []);

    const handleNext = () => {
        handleStep(activeStep);
        if (activeStep !== 2) {
            setActiveStep((prevActiveStep) => prevActiveStep + 1);
        }
    }

    const handleStep = (step) => {
        if (step === 0) {
            setCompleted1(name !== '' && folder !== '');
            step1.current.style.display = 'none';
            step2.current.style.display = 'block';
        }
        if (step === 1) {
            setCompleted2(true);
            setCompleted3(true);
            step2.current.style.display = 'none';
            step3.current.style.display = 'block';
        }
        if (step === 2) {
            setCompleted3(true);
            handleSubmit();
        }
        console.log(activeStep);
    }

    const handlePrev = () => {
        if (activeStep === 1) {
            step1.current.style.display = 'block';
            step2.current.style.display = 'none';
        }
        if (activeStep === 2) {
            step2.current.style.display = 'block';
            step3.current.style.display = 'none';
            setCompleted3(true);
        }
        setActiveStep((prevActiveStep) => prevActiveStep - 1);
    }

    const handleShare = (e) => {
        if (e.target.checked === true) {
            setPartage(true);
            setCopieDisabled(false);
        } else {
            setPartage(false);
            setCopieDisabled(true);
            setCopie(false);
        }
    }

    const handleSubmit = async () => {
        setSnackOpen(false);
        console.log('submitting...');
        if (completed1 && completed2 && completed3) {
            const res = await fetch('/api/gares', {
                method: 'POST',
                body: JSON.stringify({ name: name, type: 'Classic', folder: folder, infos: texteInfos, infos_type: typeInfos, shared: partage, copy: copie }),
                headers: { 'Content-Type': 'application/json' }
            });
            if (res.status === 200) {
                const data = await res.json();
                redirect(`/creator/gare/classique/${data.id}`);
            }
        } else {
            setSnackOpen(true);
        }
    }

    return (
        <Box sx={{ margin: '15px' }}>
            <Typography variant="h4">Nouvelle gare</Typography>
            <Box sx={{ marginTop: '20px', marginBottom: '20px' }}>
                <Stepper nonLinear activeStep={activeStep}>
                    <Step key={'general_infos'} completed={completed1}>
                        <StepButton>
                            <StepLabel>Informations générales</StepLabel>
                        </StepButton>
                    </Step>
                    <Step key={'informations_screen'} completed={completed2}>
                        <StepButton>
                            <StepLabel>&Eacute;cran d&apos;informations</StepLabel>
                        </StepButton>
                    </Step>
                    <Step key={'sharing'} completed={completed3}>
                        <StepButton>
                            <StepLabel>Partage</StepLabel>
                        </StepButton>
                    </Step>
                </Stepper>
            </Box>
            <Box ref={step1}>
                <Typography variant="h5">Informations générales</Typography>
                <TextField
                    label="Nom"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    variant="outlined"
                    margin="normal"
                    fullWidth
                    required
                />
                <Autocomplete
                    options={folders}
                    renderInput={(params) => <TextField {...params} label="Dossier" variant="outlined" margin="normal" fullWidth required />}
                    getOptionLabel={(option) => { if (option.label === 'default') return 'Dossier par défaut'; return option.label; }}
                    value={{ label: 'default' }}
                    onChange={(e, value) => setFolder(value)}
                />
                <Box sx={{ textAlign: 'right', marginTop: '20px' }}>
                    <ButtonGroup variant='contained'>
                        <Button onClick={handleNext} endIcon={<NavigateNext />}>Suivant</Button>
                    </ButtonGroup>
                </Box>
            </Box>
            <Box ref={step2} sx={{ display: 'none' }}>
                <Typography variant="h5">&Eacute;cran d&apos;informations</Typography>
                <TextField
                    label="Texte d'informations"
                    value={texteInfos}
                    onChange={(e) => setTexteInfos(e.target.value)}
                    margin="normal"
                    fullWidth
                    multiline
                    rows={4} />
                <FormLabel id='type_infos_label'>Type d&apos;informations</FormLabel>
                <RadioGroup row name='type_infos' aria-labelledby='infos_type_label' value={typeInfos} onChange={(e) => setTypeInfos(e.target.value)}>
                    <FormControlLabel value='infos_normal' control={<Radio />} label='Informations' />
                    <FormControlLabel value='infos_flash' control={<Radio />} label='Flash circulation' />
                </RadioGroup>
                <Box sx={{ textAlign: 'right', marginTop: '20px' }}>
                    <ButtonGroup variant='contained'>
                        <Button onClick={handlePrev} startIcon={<NavigateBefore />}>Précédent</Button>
                        <Button onClick={handleNext} endIcon={<NavigateNext />}>Suivant</Button>
                    </ButtonGroup>
                </Box>
            </Box>
            <Box ref={step3} sx={{ display: 'none' }}>
                <Typography variant="h5">Partage</Typography>
                <FormGroup>
                    <FormControlLabel checked={partage} control={<Checkbox onChange={handleShare} />} label='Partager cette gare' />
                    <FormControlLabel disabled={copieDisabled} checked={copie} control={<Checkbox onChange={(e) => setCopie(e.target.value)} />} label='Permettre aux autres utilisateurs de copier cette gare' />
                </FormGroup>
                <Box sx={{ textAlign: 'right', marginTop: '20px' }}>
                    <ButtonGroup variant='contained'>
                        <Button onClick={handlePrev} startIcon={<NavigateBefore />}>Précédent</Button>
                        <Button onClick={handleNext} endIcon={<Check />}>Terminer</Button>
                    </ButtonGroup>
                </Box>
            </Box>
            <Snackbar open={snackOpen} autoHideDuration={3000} message="Vous n'avez pas rempli tous les champs obligatoires !" />
        </Box>
    );
}