import React, { useEffect, useState, useContext } from "react";
import { useParams } from 'react-router-dom';
import { AuthContext } from '../../helpers/AuthContext';
import axios from "axios";
import { Formik, Form } from "formik";
import Button from '@mui/material/Button';
import { useNavigate } from "react-router-dom";
import dateFormat from "dateformat";
import 'react-toastify/dist/ReactToastify.css';
import { toast } from 'react-toastify';


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

function ReturnBike() {
    let { id } = useParams();
    let navigate = useNavigate();
    const { authState } = useContext(AuthContext);
    const [errorList, setErrorList] = useState([]);
    const [rental, setRental] = useState({});
    const [bike, setBike] = useState({});
    const [startStation, setStartStation] = useState({});
    const [endStation, setEndStation] = useState({});

    const initialValues = {
        bikeId: "",
        endStationId: id,
        id: ""
    };

    useEffect(() => {
        axios.get(`/api/rental`, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            setRental(response.data)
            setBike(response.data.bike)
            setStartStation(response.data.startStation)
        })
            .catch((error) => {
                setErrorList([]);
                setErrorList(list => [...list, (error.response.data.error ?? error.response.data.message ?? "There was a problem")])

            });
    }, [authState]);

    useEffect(() => {
        axios.get(`/api/stations/${id}`, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            setEndStation(response.data)
        })
            .catch((error) => {
                setErrorList([]);
                setErrorList(list => [...list, (error.response.data.error ?? error.response.data.message ?? "There was a problem")])
            });
    }, [id]);

    const onSubmit = (data) => {
        data.bikeId = bike.id;
        data.id = rental.id
        axios.put(`/api/rental/end`, data, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            successAlert();
            navigate("/");
        })
            .catch((error) => {
                setErrorList([]);
                setErrorList(list => [...list, (error.response.data.error ?? error.response.data.message ?? "There was a problem")])

            });
    };

    return (
        <div className="container full-vh">
            <h1 className="my-5 text-center">Return Bike at {endStation.name} Station</h1>
            {errorList.map((value, key) => {
                return (
                    <ul>
                        <li className="text-danger list-unstyled">{value}</li>
                    </ul>

                )
            })}
            {rental.id && (
                <div className="card shadow-custom">
                    <h5 class="card-header nav-bg">Your Current Rental:</h5>
                    <div className="card-body">
                        <label>Bike Serial Number</label>
                        <h6 className="card-subtitle mb-2 text-muted">{bike.serialNumber}</h6>
                        <label>Start Time:</label>
                        <h6 className="card-subtitle mb-2 text-muted">{dateFormat(rental.startTime, "h:MM:ss TT, dddd mmmm dS yyyy")}</h6>
                        <label>Start Station:</label>
                        <h6 className="card-subtitle mb-2 text-muted">{startStation.name}</h6>

                        <Formik onSubmit={onSubmit} initialValues={initialValues}>
                            <Form>
                                <Button
                                    type="submit"
                                    variant="contained"
                                    sx={{ mt: 3, mb: 2 }}
                                >
                                    Return Bike
                                </Button>
                            </Form>
                        </Formik>
                    </div>
                </div>)}
        </div>
    )
}

export default ReturnBike