import React, { useState } from 'react';
import '../styles/Admin.css'
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import Avatar from '@mui/material/Avatar';
import Button from '@mui/material/Button';
import CssBaseline from '@mui/material/CssBaseline';
import Grid from '@mui/material/Grid';
import Box from '@mui/material/Box';
import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
import Typography from '@mui/material/Typography';
import Container from '@mui/material/Container';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import { toast } from 'react-toastify';
import { Link } from 'react-router-dom';

export default function AddUser() {
    let navigate = useNavigate();
    const theme = createTheme();
    const [error, setError] = useState('');

    const initialValues = {
        firstName: "",
        lastName: "",
        username: "",
        email: "",
        password: "",
        passwordConfirmation: "",
    };

    const validationSchema = Yup.object().shape({
        firstName: Yup.string().min(1).max(50).required("You must input a first name"),
        lastName: Yup.string().min(1).max(50).required("You must input a last name"),
        username: Yup.string().min(3).max(20).required("You must input a username"),
        email: Yup.string().min(3).max(50).required("You must input a email"),
        password: Yup.string().min(6).max(40).required("You must input a password"),
        passwordConfirmation: Yup.string().oneOf([Yup.ref('password'), null], 'Passwords must match')
    });

    const successAlert = () => {
        
        toast.success("User successfully added.", {
            position: "top-center",
            autoClose: 2000,
            hideProgressBar: false,
            closeOnClick: true,
            pauseOnHover: false,
            draggable: true,
            progress: undefined,
        });
    }

    const onSubmit = (data) => {
        axios.post(`/api/auth/signup`, data, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            successAlert();
            navigate("/admin/users");
        }).catch((error) => {
            setError(error.response.data.error ?? error.response.data.message ?? "There was a problem");
        });
    };

    return (
        <div>
            <ThemeProvider theme={theme}>
                <Container sx={{ minHeight: "100vh" }} component="main" maxWidth="xs">
                    <CssBaseline />
                    <main className="w-100 bg-grey rounded-3">
                        <Box
                            sx={{
                                p: 5,
                                marginTop: 8,
                                display: 'flex',
                                flexDirection: 'column',
                                alignItems: 'center',
                            }}
                            className='contentBox rounded-3'
                        >
                            <Avatar sx={{ m: 1, bgcolor: 'secondary.main' }}>
                                <LockOutlinedIcon />
                            </Avatar>
                            <Typography component="h1" variant="h5">
                                Sign up
                            </Typography>
                            <Box sx={{ mt: 3 }}>
                                <Formik initialValues={initialValues} onSubmit={onSubmit} validationSchema={validationSchema}>
                                    <Form >
                                        <span className="text-danger">{error}</span>
                                        <Grid container spacing={2}>
                                            <Grid item xs={12} sm={6}>
                                                <label>First Name: </label>
                                                <Field
                                                    className="form-control"
                                                    name="firstName"
                                                />
                                                <ErrorMessage name="firstName" component="span" className='error-text' />
                                            </Grid>
                                            <Grid item xs={12} sm={6}>
                                                <label>Last Name: </label>
                                                <Field
                                                    className="form-control"
                                                    name="lastName"
                                                />
                                                <ErrorMessage name="lastName" component="span" className='error-text' />
                                            </Grid>
                                            <Grid item xs={12}>
                                                <label>Email: </label>
                                                <Field
                                                    className="form-control"
                                                    name="email"
                                                />
                                                <ErrorMessage name="email" component="span" className='error-text' />
                                            </Grid>
                                            <Grid item xs={12}>
                                                <label>Username: </label>
                                                <Field
                                                    className="form-control"
                                                    name="username"
                                                />
                                                <ErrorMessage name="username" component="span" className='error-text' />
                                            </Grid>
                                            <Grid item xs={12} sm={6}>
                                                <label>Password: </label>
                                                <Field
                                                    type="password"
                                                    className="form-control"
                                                    name="password"
                                                />
                                                <ErrorMessage name="password" component="span" className='error-text' />
                                            </Grid>
                                            <Grid item xs={12} sm={6}>
                                                <label>Confirm Password: </label>
                                                <Field
                                                    type="password"
                                                    className="form-control"
                                                    name="passwordConfirmation"
                                                />
                                                <ErrorMessage name="passwordConfirmation" component="span" className='error-text' />
                                            </Grid>
                                        </Grid>
                                        <Button
                                            type="submit"
                                            fullWidth
                                            variant="contained"
                                            sx={{ mt: 3, mb: 2 }}
                                        >
                                            Add User
                                        </Button>
                                        <Link to={"/admin/users"}><button className="btn btn-secondary green-btn w-100">Back to Users</button></Link>
                                    </Form>
                                </Formik>
                            </Box>
                        </Box>
                    </main>
                </Container>
            </ThemeProvider>
        </div>
    )
}
