import React, { useEffect, useState, useContext } from "react";
import { useParams } from 'react-router-dom';
import axios from "axios";
import 'react-toastify/dist/ReactToastify.css';
import { toast } from 'react-toastify';
// import { ToastContainer } from 'react-toastify';
import { AuthContext } from '../../helpers/AuthContext';
import { Formik, Form, Field, ErrorMessage } from "formik";
import Button from '@mui/material/Button';
// import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import * as Yup from "yup";
import "./Rental.scss"
import "../../App.css"
import { ThreeCircles } from 'react-loader-spinner';


function RentBike() {
    let { id } = useParams();
    const [isLoading, setLoading] = useState(true);
    const [station, setStation] = useState({});
    const [listOfBikes, setListOfBikes] = useState([]);
    const [error, setError] = useState('');
    let navigate = useNavigate();
    const { authState } = useContext(AuthContext);


    const successAlert = () => {
        toast.success("You have rented a bike successfully!", {
            position: "top-center",
            autoClose: 2000,
            hideProgressBar: false,
            closeOnClick: true,
            pauseOnHover: false,
            draggable: true,
            progress: undefined,
        });
    }


    useEffect(() => {
        axios.get(`/api/stations/${id}`, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            setLoading(false);
            setStation(response.data);
            setListOfBikes(response.data.bikes);
        }).catch((error) => {
            if (error.response.data.message) {
                setError(error.response.data.message);
            }
        });
    }, [authState, id]);

    const initialValues = {
        bikeId: ""
    };

    const validationSchema = Yup.object().shape({
        bikeId: Yup.string().required("You must select a bike"),
    });


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

    if (isLoading) {
        return (
            <div className="loadingContainer">
                <ThreeCircles
                    type="ThreeDots"
                    color="#00b22d"
                    height={100}
                    width={100}
                //3 secs
                />
            </div>
        )
    } else {
        return (
            <div className="container w-100 full-vh">
                <h1 className="text-center my-5">Station: {station.name} </h1>
                {listOfBikes.length > 0 ? (
                    <Formik onSubmit={onSubmit} initialValues={initialValues} validationSchema={validationSchema}>
                        <Form>
                            <section className="container nav-bg rounded-3 p-5 ">
                                <h5>Choose your ride!</h5>
                                <div className="row">
                                    <div className="col-sm-12">
                                        {listOfBikes.map((value, key) => (
                                            <div key={key} className="mb-3">
                                                <Field className="radioInput" type="radio" id={`${value.id}`} name="bikeId" value={`${value.id}`} />
                                                <label className="radioLabel" htmlFor={`${value.id}`}>
                                                    <h2>Bike Number: {value.serialNumber}</h2>
                                                    <p>Bike Type: {value.bikeType}</p>
                                                </label>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            </section>
                            <div className="d-flex justify-content-center">
                                {authState && authState.provisionAccess ? (
                                    <>
                                        <Button
                                            variant="contained"
                                            sx={{ mt: 3, mb: 2, bgcolor: "#9ad5e9" }}
                                            className="text-white m-2 align-middle"
                                            type="submit"
                                        >
                                            Rent Bike
                                        </Button>
                                    </>
                                ) : (
                                    <Button
                                        variant="contained"
                                        sx={{ mt: 3, mb: 2, bgcolor: "#9ad5e9" }}
                                        className="text-white m-2 align-middle"
                                        onClick={
                                            () => {
                                                navigate(`/pricing`)
                                            }
                                        }
                                    >
                                        Subscribe now to rent!
                                    </Button>
                                )}
                            </div>
                            <p className="text-center"><ErrorMessage name="bikeId" component="span" className='error-text' /></p>
                            <span className="text-danger">{error}</span>
                        </Form>
                    </Formik>
                ) : (
                    <section className="container bg-white rounded-3 p-5 ">
                        <h2 className="text-center">It looks like there aren't any bikes at this station...</h2>
                        <br />
                        <p className="text-center"><small>Go find a bike and park it here for a discount on your subscription!</small></p>
                    </section>
                )}

            </div>
        )

    }
}

export default RentBike