import { Button, Checkbox, Dialog, DialogActions, DialogContent, DialogTitle, TextField, Box, FormControlLabel, Typography } from "@mui/material";
import * as React from "react";

export default function EditUserDialog({ open, user, handleModify, handleClose, handleDelete, handleDisable, handleEnable }) {

    const [username, setUsername] = React.useState(user.USERNAME);
    const [email, setEmail] = React.useState(user.EMAIL);
    const [email_valid, setEmailValid] = React.useState(user.EMAIL_VALID);

    React.useEffect(() => {
        setUsername(user.USERNAME);
        setEmail(user.EMAIL);
        setEmailValid(user.EMAIL_VALID);
    }, [user]);

    const handleMailValidation = async () => {
        const response = await fetch(`/api/mail/validate`, {
            method: 'POST',
            body: JSON.stringify({ email: user.EMAIL }),
            headers: { 'Content-Type': 'application/json' }
        });

        if (response.ok) {
            console.log('Email sent');
        }
    }

    const handlePrepareModify = () => {
        handleModify(user.USER_ID, username, email, email_valid);
    }

    return (
        <Dialog open={open} onClose={handleClose} maxWidth='sm' fullWidth>
            <DialogTitle>Modifier l&apos;utilisateur {user.USERNAME}</DialogTitle>
            <DialogContent>
                <Box display='flex' flexDirection='column'>
                    <TextField id="username" label="Nom d'utilisateur" onChange={(e) => setUsername(e.target.value)} value={username} />
                    <TextField id="email" label="Adresse email" onChange={(e) => setEmail(e.target.value)} value={email} />
                    {email_valid ? <></> : <Button variant='contained' color='primary' onClick={(e) => handleMailValidation()}>Envoyer le mail de validation</Button>}
                    <FormControlLabel control={<Checkbox id="email_valid" onChange={(e) => setEmailValid(e.target.checked)} checked={email_valid} />} label='Email validé' />
                    <Typography variant='h5' sx={{ color: 'red', marginTop: '10px', marginBottom: '10px' }}>Zone danger !</Typography>
                    {user.ENABLED == 'True' ? <Button variant='contained' color='warning' onClick={handleDisable} sx={{ margin: '10px' }}>Désactiver l&apos;utilisateur</Button> : <Button variant='contained' color='success' onClick={(e) => handleEnable(user.USER_ID)} sx={{ margin: '10px' }}>Activer l&apos;utilisateur</Button>}
                    <Button variant='contained' color='error' onClick={handleDelete} sx={{ margin: '10px' }}>Supprimer l&apos;utilisateur</Button>
                </Box>
            </DialogContent>
            <DialogActions>
                <Button variant='text' color='default' onClick={handleClose}>Annuler</Button>
                <Button variant='text' color='primary' onClick={handlePrepareModify}>Modifier</Button>
            </DialogActions>
        </Dialog>
    );
} 