import React, { useState } from 'react';
import { Formik, Form, Field, ErrorMessage } from "formik";
import 'react-toastify/dist/ReactToastify.css';
import { toast } from 'react-toastify';
import * as Yup from "yup";
import axios from "axios";
import { useNavigate } from "react-router-dom";
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/Admin.css'
import { Link } from 'react-router-dom';

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

    const initialValues = {
        name: "",
        totalSlots: "",
        latitude: "",
        longitude: "",
    };

    const validationSchema = Yup.object().shape({
        name: Yup.string().min(1).max(100).required("You must input a station name"),
        totalSlots: Yup.number().positive().integer().min(0).max(30, "Number of slots must not exceed 30").required("You must input the number of bike slots"),
        latitude: Yup.string().min(1).max(100).required("You must input a latitude").matches("-?[0-9]\d*(\.\d+)?$", "Invalid latitude"),
        longitude: Yup.string().min(1).max(100).required("You must input a longitude").matches("-?[0-9]\d*(\.\d+)?$", "Invalid longitude")
    });


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

    const onSubmit = (data) => {

        axios.post(`/api/admin/stations`, data, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            successAlert();
            navigate("/admin/stations");
        })
            .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-white rounded-3 shadow-sm">
                        <Box
                            sx={{
                                p: 5,
                                marginTop: 8,
                                display: 'flex',
                                flexDirection: 'column',
                                alignItems: 'center',
                            }}
                            className='contentBox rounded-3'
                        >
                            <Typography component="h1" variant="h5">
                                Add Station
                            </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>Station Name: </label>
                                                <Field
                                                    className="form-control"
                                                    name="name"
                                                />
                                                <ErrorMessage name="name" component="span" className='error-text' />
                                            </Grid>
                                            <Grid item xs={12} sm={6}>
                                                <label>Number of Slots: </label>
                                                <Field
                                                    type="number"
                                                    className="form-control"
                                                    name="totalSlots"
                                                    min="0"
                                                    max="30"
                                                />
                                                <ErrorMessage name="totalSlots" component="span" className='error-text' />
                                            </Grid>
                                            <Grid item xs={12}>
                                                <label>Latitude: </label>
                                                <Field
                                                    className="form-control"
                                                    name="latitude"
                                                />
                                                <ErrorMessage name="latitude" component="span" className='error-text' />
                                            </Grid>
                                            <Grid item xs={12}>
                                                <label>Longitude: </label>
                                                <Field
                                                    className="form-control"
                                                    name="longitude"
                                                />
                                                <ErrorMessage name="longitude" component="span" className='error-text' />
                                            </Grid>
                                            <Grid item xs={12}>

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