import React, {useState} from 'react';
import 'react-toastify/dist/ReactToastify.css';
import { toast } from 'react-toastify';
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 Typography from '@mui/material/Typography';
import Container from '@mui/material/Container';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import '../../styles/LoginRegistration.css';
import { PedalBikeRounded } from '@mui/icons-material';
//import DatePicker from "react-datepicker";
import {
  Select,
  MenuItem,
} from "@material-ui/core";
import FormControl from '@mui/material/FormControl';
import { Link } from 'react-router-dom';


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

    const initialValues = {
        serialNumber: "",
        bikeType: ""
    };


    const validationSchema = Yup.object().shape({
        serialNumber: Yup.string().min(10).max(10).required("Enter Serial number including 2 uppercase letter and 8 digits"),
        bikeType: Yup.string().required("Choose Bike Type"),
    });

  const CustomizedSelectForFormik = ({ children, form, field }) => {
  const { name, value } = field;
  const { setFieldValue } = form;

  return (
    <Select
      name={name}
      value={value}
      onChange={e => {
        setFieldValue(name, e.target.value);
      }}
    >
      {children}
    </Select>
  );
};

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

    const onSubmit = (data) => {
        axios.post(`https://hellovelo.herokuapp.com/api/admin/bikes`, data, {
        headers: {
            Authorization: 'Bearer ' + localStorage.getItem('accessToken')
        }
    }).then((response) => {
            successAlert();
            navigate("/admin/bikes");
        })
        .catch((error) => {
            toast.error("Failed to add bike")
            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 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' }}>
                            <PedalBikeRounded />
                        </Avatar> 
                        <Typography component="h1" variant="h5">
                            Add Bike
                        </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}>
                                            <label>Serial Number: </label>
                                            <Field
                                                className="form-control"
                                                name="serialNumber"
                                            />
                                            <ErrorMessage name="serialNumber" component="span" className='error-text' />
                                        </Grid>
                                        <Grid item xs={12}>
                                            <FormControl>
                                                <label >Bike Type:</label>
                                                    <Field name="bikeType" component={CustomizedSelectForFormik} fullWidth>
                                                        <MenuItem value={"STANDARD"} fullWidth>STANDARD</MenuItem>
                                                        <MenuItem value={"ELECTRIC"} fullWidth>ELECTRIC</MenuItem>
                                                    </Field>
                                            </FormControl>
                                            <br/>
                                            <ErrorMessage name="bikeType" component="span" className='error-text' />
                                        </Grid>

                                    </Grid>
                                    <Button
                                        type="submit"
                                        fullWidth
                                        variant="contained"
                                        sx={{ mt: 3, mb: 2 }}
                                    >
                                        Add Bike
                                    </Button>
                                    <Link to={"/admin/bikes"}><button className="btn btn-secondary green-btn w-100">Back to Bikes</button></Link>
                                    <Grid container justifyContent="flex-end">
                                    </Grid>
                                </Form>
                            </Formik>
                        </Box>
                    </Box>
                </main>
            </Container>
        </ThemeProvider>
    </div>
    )
}
