import React, { useState, useContext, useEffect } from 'react';
import { AuthContext } from "../helpers/AuthContext";
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 './styles/LoginRegistration.css'


export default function Registration() {

    let navigate = useNavigate();
    const theme = createTheme();
    const [error, setError] = useState('');
    const { setAuthState } = useContext(AuthContext)

    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')
    });

    useEffect(() => {
        window.scrollTo(0, 0)
    }, [])

    const onSubmit = (data, { resetForm }) => {
        axios.post(`/api/auth/signup`, data).then(() => {
            //If registration was successful, sign the user in.
            let userData = { username: data.username, password: data.password };
            axios.post(`/api/auth/signin`, userData).then((response) => {
                localStorage.setItem("accessToken", response.data.accessToken);
                response.data.roles = response.data.roles.map(role => {
                    return role.replace('ROLE_', '');
                });
                delete response.data.accessToken
                delete response.data.tokenType
                setAuthState({
                    ...response.data,
                    loggedIn: true
                });
                navigate("/pricing");
            })
        }).catch((error) => {
            resetForm({ values: { ...data, password: "", passwordConfirmation: "" } });
            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-white rounded-3 shadow-sm">
                        <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 >
                                        <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 item xs={12}>
                                                <span className="text-danger">{error}</span>
                                            </Grid>
                                        </Grid>
                                        <Button
                                            type="submit"
                                            fullWidth
                                            variant="contained"
                                            sx={{ mt: 3, mb: 2, bgcolor: "#EEB2A5" }}
                                        >
                                            Sign Up
                                        </Button>
                                        <Grid container justifyContent="flex-end">
                                            <Grid item xs={12}>
                                                <Button
                                                    size="small"
                                                    onClick={
                                                        () => {
                                                            navigate("/login")
                                                        }
                                                    }
                                                >
                                                    Already have an account? Log in!
                                                </Button>
                                            </Grid>
                                        </Grid>
                                    </Form>
                                </Formik>
                            </Box>
                        </Box>
                    </main>
                </Container>
            </ThemeProvider>
        </div>
    )
}
