import React, { useEffect, useState } from "react";
import { useParams } from 'react-router-dom';
import axios from "axios";
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
import TablePagination from '@mui/material/TablePagination';
import { MenuItem } from "@mui/material";
import Button from '@mui/material/Button';
import { Checkbox } from "@mui/material";
import { useNavigate } from "react-router-dom";
import { Formik, Form, Field, ErrorMessage } from "formik";
import Select from '@mui/material/Select';
import * as Yup from "yup";
import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { Link } from 'react-router-dom';


function TransferBikes() {
    let { id } = useParams();
    const [error, setError] = useState('');
    const [data, setData] = useState('');
    const [listOfBikes, setListOfBikes] = useState([]);
    const [listOfTransferStations, setListOfTransferStations] = useState([]);
    let navigate = useNavigate();

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

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

    useEffect(() => {
        axios.get(`/api/admin/stations/transfer/list/${id}`, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            setListOfTransferStations(response.data)
        })
            .catch((error) => {
                if (error.response.data.message) {
                    setError(error.response.data.message);
                }
            });
    }, [id]);

    function createData(id, serialNumber, bikeType, lastMaintenance, currentlyInUse, status) {
        return { id, serialNumber, bikeType, lastMaintenance, currentlyInUse, status };
    }

    const rows = listOfBikes.map((value) => (
        createData(value.id, value.serialNumber, value.bikeType, value.lastMaintenance, value.currentlyInUse, value.status)
    ))

    const [page, setPage] = React.useState(0);
    const [rowsPerPage, setRowsPerPage] = React.useState(5);


    const handleChangePage = (event, newPage) => {
        setPage(newPage);
    };

    const handleChangeRowsPerPage = (event) => {
        setRowsPerPage(parseInt(event.target.value, 10));
        setPage(0);
    };

    const initialValues = {
        checkboxOptions: [],
        transferStation: ""

    };

    const validationSchema = Yup.object().shape({
        checkboxOptions: Yup.array().min(1, "You must select at least 1 bike").required(),
        transferStation: Yup.number().required("You must select a transfer station"),
    });

    const onSubmit = (data) => {

        console.log(data);

        axios.put(`/api/admin/bikes/transfer`, data, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            console.log(response.data)
            successAlert();
            navigate("/admin/stations");
        })
            .catch((error) => {
                console.log(error.response.data)
                setError(error.response.data.error ?? error.response.data.message ?? "There was a problem");

            });
    };



    return (
        <div className="full-vh">
            <div className='d-flex justify-content-center bg-grey '>
                {/* <span className="text-danger">{error}</span> */}
                <Formik onSubmit={onSubmit} initialValues={initialValues} validationSchema={validationSchema}>
                    <Form >
                        <TableContainer
                            className='mt-5 w-100 shadow'
                            component={Paper}
                        >
                            <h1 className='text-center mt-2'>List of Bikes for {data.name}</h1>
                            {/* <ul className="list-unstyled">
                                <li><ErrorMessage name="checkboxOptions" component="span" className='error-text' /></li>
                                <li><ErrorMessage name="transferStation" component="span" className='error-text' /></li>
                            </ul> */}
                            <Table className='shadow-sm mb-3' sx={{ minWidth: 850 }} aria-label="simple table">
                                <TableHead className='shadow-sm'>
                                    <TableRow>
                                        <TableCell align="right">ID</TableCell>
                                        <TableCell align="right">Serial Number</TableCell>
                                        <TableCell align="right">Bike Type</TableCell>
                                        <TableCell align="right">Last Maintenance Date</TableCell>
                                        <TableCell align="right">Currently In Use</TableCell>
                                        <TableCell align="right">Status</TableCell>
                                        <TableCell align="center">Transfer</TableCell>
                                    </TableRow>
                                </TableHead>
                                <TableBody>
                                    {rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((row, index) => (
                                        <TableRow
                                            key={row.id}
                                            sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
                                        >
                                            <TableCell align="right">{row.id}</TableCell>
                                            <TableCell align="right">{row.serialNumber}</TableCell>
                                            <TableCell align="right">{row.bikeType}</TableCell>
                                            <TableCell align="right">{row.lastMaintenance}</TableCell>
                                            <TableCell align="right">{row.currentlyInUse.toString()}</TableCell>
                                            <TableCell align="right">{row.status}</TableCell>
                                            <TableCell align="right">
                                                <Field name="checkboxOptions" type="checkbox" as={Checkbox} value={`${row.id}`} />
                                                {/* <Button className="bg-secondary text-white mx-2" onClick={() => { editStation(row.id) }}>Edit!</Button>
                                    <Button className="bg-danger text-white mx-2" onClick={() => { deleteStation(row.id) }}>Delete</Button>
                                    <Button className="bg-primary text-white" onClick={() => { transferBikes(row.id) }}>Transfer Bikes</Button> */}

                                            </TableCell>
                                        </TableRow>
                                    ))}
                                </TableBody>
                            </Table>
                            <div className='d-flex flex-wrap justify-content-between'>
                                <Link to={"/admin/stations"}><button className="btn btn-secondary green-btn m-2">Back to Stations</button></Link>



                                {listOfBikes.length > 0 && (
                                    <>
                                        {/* <label>Transfer Station with available slots: </label> */}
                                        <Field as={Select} name="transferStation" displayEmpty >
                                            <MenuItem value='' selected="selected">Select a transfer station with available slots</MenuItem>
                                            {listOfTransferStations.map((value, key) => (
                                                <MenuItem value={`${value.id}`}>{value.name}</MenuItem>
                                            ))}
                                        </Field>

                                        <Button
                                            className="bg-info text-white m-2 align-middle"
                                            type="submit"
                                        >
                                            Transfer Bikes
                                        </Button>
                                        <span className="text-danger">{error}</span>
                                        <ul className="list-unstyled">
                                            <li><ErrorMessage name="checkboxOptions" component="span" className='error-text' /></li>
                                            <li><ErrorMessage name="transferStation" component="span" className='error-text' /></li>
                                        </ul>
                                    </>
                                )}

                                {/* <button type="submit" className="btn btn-primary">Transfer Bikes</button> */}

                                <TablePagination
                                    rowsPerPageOptions={[5, 10, 25]}
                                    component="div"
                                    count={rows.length}
                                    rowsPerPage={rowsPerPage}
                                    page={page}
                                    onPageChange={handleChangePage}
                                    onRowsPerPageChange={handleChangeRowsPerPage}
                                ></TablePagination>
                            </div>
                        </TableContainer>
                    </Form>
                </Formik>
            </div>
        </div>
    )
}

export default TransferBikes