import React from 'react';
import axios from 'axios';
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
//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';
import 'react-toastify/dist/ReactToastify.css';
import { toast } from 'react-toastify';

export default function MaintenanceList() {
    const [listOfBikes, setListOfBikes] = useState([]);
    let navigate = useNavigate();

        const successAlert = () => {
        // window.alert("Invalid Credentials");
        toast.success("Bike is maintained sucessfully!", {
            position: "top-center",
            autoClose: 2000,
            hideProgressBar: false,
            closeOnClick: true,
            pauseOnHover: false,
            draggable: true,
            progress: undefined,    
        });
    }

    useEffect(() => {
        axios.get(`/api/admin/maintenance`, {
        headers: {
            Authorization: 'Bearer ' + localStorage.getItem('accessToken')
        }
    }).then((response) => {
            console.log(response.data)
            setListOfBikes(response.data);
        });
    }, []);

    const updateTable = () => {
        axios.get(`/api/admin/maintenance`, {
        headers: {
            Authorization: 'Bearer ' + localStorage.getItem('accessToken')
        }
    }).then((response) => {
            setListOfBikes(response.data);
        });
    }

    const maintained = (id) => {
        axios.post(`/api/admin/maintenance/${id}`, null, {
        headers: {
            Authorization: 'Bearer ' + localStorage.getItem('accessToken')
        }
    }).then((response) => {
            console.log(response);
            updateTable();
            successAlert();
        });
    };

    // const editBike = (id) => {
    //     navigate(`/admin/bikes/update/${id}`);
    // };

    // const addBike = () => {
    //     navigate('/admin/bikes/create')
    // }

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

    const rows = listOfBikes.map((value) => (
        createData(value.id, value.bikeType, value.currentlyInUse, value.lastMaintenance, value.serialNumber, 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);
    };

    return (
        <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 Bikes In Maintenance</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">Bike Type</TableCell>
                            <TableCell align="right">Currently In Use</TableCell>
                            <TableCell align="right">Last Maintenance</TableCell>
                            <TableCell align="right">Serial Number</TableCell>
                            <TableCell align="right">Status</TableCell>
                            <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.bikeType}</TableCell>
                                <TableCell align="right">{row.currentlyInUse.toString()}</TableCell>
                                <TableCell align="right">{row.lastMaintenance}</TableCell>
                                <TableCell align="right">{row.serialNumber}</TableCell>
                                 <TableCell align="right">{row.status}</TableCell>
                                <TableCell align="right">
                                    <Button className="bg-success text-white mx-2" onClick={() => { maintained(row.id) }}>Maintained</Button>
                                </TableCell>
                            </TableRow>
                        ))}
                    </TableBody>
                </Table>
                <div className='d-flex flex-wrap justify-content-between'>
                    {/* <Button
                        className="bg-info text-white m-2 align-middle"
                        onClick={addBike}
                    >
                        Add Bike
                    </Button> */}
                    <TablePagination
                        rowsPerPageOptions={[5, 10, 25]}
                        component="div"
                        count={rows.length}
                        rowsPerPage={rowsPerPage}
                        page={page}
                        onPageChange={handleChangePage}
                        onRowsPerPageChange={handleChangeRowsPerPage}
                    ></TablePagination>
                </div>
            </TableContainer>
        </div>

    )
}