import React from 'react';
import axios from 'axios';
import { useEffect, useState, useContext } from 'react';
import { useNavigate } from 'react-router-dom';
import { AuthContext } from '../helpers/AuthContext';
//MUI
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 Button from '@mui/material/Button';

function UserStationList() {

    const [listOfStations, setListOfStations] = useState([]);
    const { authState } = useContext(AuthContext);
    let navigate = useNavigate();

    useEffect(() => {
        if (authState.provisionAccess === false) {
            return navigate(`/pricing`)
        }
        axios.get(`/api/stations`, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            setListOfStations(response.data);
        });
    }, [authState, navigate]);

    const rentBike = (id) => {
        navigate(`/stations/rent-bike/${id}`);
    };

    const returnBike = (id) => {
        navigate(`/stations/return-bike/${id}`);
    };

    function createData(id, name, status, totalSlots, availableSlots, numberOfBikes) {
        return { id, name, status, totalSlots, availableSlots, numberOfBikes };
    }

    const rows = listOfStations.map((value) => (
        createData(value.id, value.name, value.status, value.totalSlots, value.availableSlots, value.numberOfBikes)
    ))

    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);
    };

    return (
        <div className='full-vh'>
            <div className='d-flex justify-content-center bg-grey '>
                <TableContainer
                    className='mt-5 w-75 shadow'
                    component={Paper}
                >
                    <h1 className='text-center mt-2'>List of Stations</h1>
                    <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">Station Name</TableCell>
                                <TableCell align="right">Status</TableCell>
                                <TableCell align="center">Total Slots</TableCell>
                                <TableCell align="center">Empty Slots</TableCell>
                                <TableCell align="center">Number of Bikes</TableCell>
                                {authState.roles && authState.roles.includes('USER') && (<TableCell align="center">Actions</TableCell>)}

                            </TableRow>
                        </TableHead>
                        <TableBody>
                            {rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((row) => (
                                <TableRow
                                    key={row.id}
                                    sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
                                >
                                    <TableCell align="right">{row.id}</TableCell>
                                    <TableCell align="right">{row.name}</TableCell>
                                    <TableCell align="right">{row.status}</TableCell>
                                    <TableCell align="right">{row.totalSlots}</TableCell>
                                    <TableCell align="right">{row.availableSlots}</TableCell>
                                    <TableCell align="right">{row.numberOfBikes}</TableCell>
                                    {authState.roles && authState.roles.includes('USER') && (
                                        <TableCell align="right">
                                            <Button className="bg-info text-white mx-2" onClick={() => { rentBike(row.id) }}>Rent Bike</Button>
                                            <Button className="bg-secondary text-white mx-2" onClick={() => { returnBike(row.id) }}>Return Bike</Button>
                                        </TableCell>
                                    )}

                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                    <div className='d-flex flex-wrap justify-content-between'>
                        <TablePagination
                            rowsPerPageOptions={[5, 10, 25]}
                            component="div"
                            count={rows.length}
                            rowsPerPage={rowsPerPage}
                            page={page}
                            onPageChange={handleChangePage}
                            onRowsPerPageChange={handleChangeRowsPerPage}
                        ></TablePagination>
                    </div>
                </TableContainer>
            </div>
        </div>
    )
}

export default UserStationList