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 Pagination from 'react-bootstrap/Pagination'

export default function BikeList() {
    const [listOfBikes, setListOfBikes] = useState([]);
    const [rowsPerPage] = React.useState(4);
    const [page] = React.useState(0);
    const [currPage, setCurrPage] = React.useState(1);
    const [totalBikePages, setBikeTotalPages] = useState();
    const [totalBikeElements, setTotalBikeElements] = useState();
    const [sortToggle1, setSortToggle1] = useState(true);
    const [sortToggle2, setSortToggle2] = useState(true);
    const [sortToggle3, setSortToggle3] = useState(true);
    const [sortToggle4, setSortToggle4] = useState(true);
    let sortDirection = sortToggle1
    let sortField = "id";
    const [searchText, setSearchText] = useState("");

    let navigate = useNavigate();

    useEffect(() => {
        axios.get(`/api/admin/bikes/paginated?pageNumber=${currPage - 1}&pageSize=${rowsPerPage}&sortBy=id&sortDir=asc`, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            console.log(response.data)
            setListOfBikes(response.data.content);
            setBikeTotalPages(response.data.totalPages);
            setTotalBikeElements(response.data.totalElements);
            setCurrPage(response.data.number + 1);
            console.log(currPage);
        });
    }, []);

    const updateTable = (currPage) => {
        let sortDir = sortDirection ? "asc" : "desc";
        axios.get(`/api/admin/bikes/paginated?pageNumber=${currPage - 1}&pageSize=${rowsPerPage}&sortBy=${sortField}&sortDir=${sortDir}`, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            console.log(response.data)
            setListOfBikes(response.data.content);
            setBikeTotalPages(response.data.totalPages);
            setTotalBikeElements(response.data.totalElements);
            setCurrPage(response.data.number + 1);
            console.log(currPage);
        });
    }


    const handleSearch = () => {
        let sortDir = sortDirection ? "asc" : "desc"
        axios.get(`/api/admin/bikes/search/${searchText}?pageNumber=${currPage - 1}&pageSize=${rowsPerPage}&sortBy=${sortField}&sortDir=${sortDir}`, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            console.log(response.data)
            setListOfBikes(response.data.content);
            setBikeTotalPages(response.data.totalPages);
            setTotalBikeElements(response.data.totalElements);
            setCurrPage(response.data.number + 1);
            console.log(currPage);
            setSearchText(searchText);
            console.log(searchText);
        });
    }


    const updateHandleSearch = (currPage) => {
        let sortDir = sortDirection ? "asc" : "desc";
        axios.get(`/api/admin/bikes/search/${searchText}?pageNumber=${currPage - 1}&pageSize=${rowsPerPage}&sortBy=${sortField}&sortDir=${sortDir}`, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            console.log(response.data)
            setListOfBikes(response.data.content);
            setBikeTotalPages(response.data.totalPages);
            setTotalBikeElements(response.data.totalElements);
            setCurrPage(response.data.number + 1);
            console.log(currPage);
            setSearchText(searchText);
            console.log(searchText);
        });
    }


    const sortDataId = () => {
        sortField = "id";
        if (sortToggle1 === true) {
            setSortToggle1(false);
            sortDirection = false;
        } else {
            setSortToggle1(true);
            sortDirection = true;
        }
        if (searchText) {
            updateHandleSearch(currPage);
        } else {
            updateTable(currPage);
        }
    }

    const sortDataCurrUse = () => {
        sortField = "currentlyInUse";
        if (sortToggle2 === true) {
            setSortToggle2(false);
            sortDirection = false;
        } else {
            setSortToggle2(true);
            sortDirection = true;
        }
        if (searchText) {
            updateHandleSearch(currPage);
        } else {
            updateTable(currPage);
        }
    }

    const sortDataSNumber = () => {
        sortField = "serialNumber";
        if (sortToggle3 === true) {
            setSortToggle3(false);
            sortDirection = false;
        } else {
            setSortToggle3(true);
            sortDirection = true;
        }
        if (searchText) {
            updateHandleSearch(currPage);
        } else {
            updateTable(currPage);
        }
    }

    const sortDataLastMaintenance = () => {
        sortField = "lastMaintenance";
        if (sortToggle4 === true) {
            setSortToggle4(false);
            sortDirection = false;
        } else {
            setSortToggle4(true);
            sortDirection = true;
        }
        if (searchText) {
            updateHandleSearch(currPage);
        } else {
            updateTable(currPage);
        }
    }


    const firstPage = () => {
        let firstPage = 1;
        if (currPage > firstPage) {
            if (searchText) {
                setCurrPage(1);
                updateHandleSearch(firstPage);
            }
            else {
                setCurrPage(1);
                updateTable(firstPage);
            }
        }
    };

    const prevPage = () => {
        let prevPage = 1;
        let thisPage = currPage;
        if (currPage > prevPage) {

            if (searchText) {
                setCurrPage(currPage - 1);
                updateHandleSearch(currPage - 1);
            }
            else {
                setCurrPage(currPage - 1);
                updateTable(thisPage - 1);
            }

        }
    };

    const lastPage = () => {
        let condition = Math.ceil(totalBikeElements / rowsPerPage);
        if (currPage < condition) {
            setCurrPage(condition);
            if (searchText) {
                updateHandleSearch(condition);
            } else {
                updateTable(condition);
            }
        }
    };

    const nextPage = () => {
        let thisPage = currPage;
        if (
            currPage <
            Math.ceil(totalBikeElements / rowsPerPage)
        ) {
            console.log(totalBikeElements);
            console.log(Math.ceil(totalBikeElements / rowsPerPage));
            //handleSearch(thisPage+1);
            console.log(searchText);
            if (searchText !== "") {
                setCurrPage(currPage + 1);
                updateHandleSearch(thisPage + 1);
            } else {
                setCurrPage(currPage + 1);
                updateTable(thisPage + 1);
            }
        }
    };

    const cancelSearch = () => {
        setSearchText("");
        updateTable(currPage);

    }


    // const deleteBike = (id) => {
    //     axios.delete(`/api/admin/bikes/${id}`, {
    //         //FIXME: temporary - until AUTHSTATE is working
    //         headers: { role: 'ADMIN' },
    //         // headers: { role: localStorage.getItem("accessToken") },
    //     }).then(() => {
    //         updateTable();
    //     });
    // };

    const deleteBike = (id) => {
        navigate(`/admin/bikes/delete/${id}`);
    };

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

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

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

    const rows = listOfBikes.map((value) => (
        createData(value.id, value.bikeType, value.currentlyInUse, value.lastMaintenance, value.serialNumber, value.status, (value.station ? (value.station.name) : "Not Stationed"))
    ))

    //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='map-search w-100 d-flex justify-content-center align-items-center'>
                <div className="d-flex justify-content-center align-items-center">
                    <input
                        type="search"
                        className="form-control rounded my-3 input-group rounded w-75 "
                        placeholder=" Search here ..."
                        aria-label="Search"
                        aria-describedby="Search"
                        onChange={(event) => {
                            setSearchText(event.target.value);
                            //myPage = 1;
                        }}
                        value={searchText}
                    // pattern="[A-Za-z][0-9][A-Za-z] [0-9][A-Za-z][0-9]"
                    />

                    <button
                        className="w-auto search2-btn rounded-circle mx-1 shadow"
                        type="submit"
                        onClick={handleSearch}
                    >
                        <svg
                            xmlns="http://www.w3.org/2000/svg"
                            width="16"
                            height="16"
                            className="bi bi-search"
                            viewBox="0 0 16 16"
                        >
                            <path
                                d="M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z">
                            </path>
                        </svg>
                    </button>
                    <button
                        className="w-auto close-btn rounded-circle shadow"
                        type="submit"
                        onClick={cancelSearch}
                    //onClick={handleSearch}
                    >
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-x-lg" viewBox="0 0 16 16">
                            <path fill-rule="evenodd" d="M13.854 2.146a.5.5 0 0 1 0 .708l-11 11a.5.5 0 0 1-.708-.708l11-11a.5.5 0 0 1 .708 0Z" />
                            <path fill-rule="evenodd" d="M2.146 2.146a.5.5 0 0 0 0 .708l11 11a.5.5 0 0 0 .708-.708l-11-11a.5.5 0 0 0-.708 0Z" />
                        </svg>
                    </button>

                    {/* <span className="text-danger">{error}</span>
                        <ul>
                            {errorList.map((value) => {
                                return (
                                    <li className="text-danger list-unstyled">{value}</li>
                                )
                            })}
                        </ul> */}
                </div>
            </div>
            <div className='d-flex justify-content-center bg-grey '>
                <TableContainer
                    className='mt-5 w-75 shadow'
                    component={Paper}
                >
                    <Button
                        className="bg-info text-white m-2 align-middle"
                        onClick={
                            () => {
                                navigate(`/admin/bikes/deleted-bikes`)
                            }
                        }
                    >
                        Deleted Bikes
                    </Button>
                    <h1 className='text-center mt-2'>List of Bikes</h1>
                    <Table className='shadow-sm mb-3' sx={{ minWidth: 850 }} aria-label="simple table">
                        <TableHead className='shadow-sm'>
                            <TableRow>
                                <TableCell align="right" onClick={sortDataId}>ID{" "}<span className={sortToggle1 ? "arrow arrow-down" : "arrow arrow-up"}> {" "} </span></TableCell>
                                <TableCell align="right" >Bike Type</TableCell>
                                <TableCell align="right" onClick={sortDataCurrUse}>Currently In Use{" "}<span className={sortToggle2 ? "arrow arrow-down" : "arrow arrow-up"}> {" "} </span></TableCell>
                                <TableCell align="right" onClick={sortDataLastMaintenance}>Last Maintenance{" "}<span className={sortToggle3 ? "arrow arrow-down" : "arrow arrow-up"}> {" "} </span></TableCell>
                                <TableCell align="right" onClick={sortDataSNumber}>Serial Number{" "}<span className={sortToggle4 ? "arrow arrow-down" : "arrow arrow-up"}> {" "} </span></TableCell>
                                <TableCell align="right">Status</TableCell>
                                <TableCell align="right">station Name</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>
                                    {row.StationName !== null && (<TableCell align="right">{row.StationName}</TableCell>)}
                                    <TableCell align="right">
                                        <Button className="bg-secondary text-white mx-2" onClick={() => { editBike(row.id) }}>Edit!</Button>
                                        {!row.currentlyInUse && (<Button className="bg-danger text-white" onClick={() => { deleteBike(row.id) }}>Delete</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>
                        <>
                            {listOfBikes.length > 0 ?
                                <>
                                    <div style={{ float: "left", marginLeft: "5px" }}>
                                        Showing Page {currPage} of {totalBikePages}
                                    </div>
                                    <div style={{ float: "right", marginRight: "5px" }}>
                                        <Pagination >
                                            <Pagination.First
                                                type="button"
                                                className="page-item"
                                                variant="outline-info"
                                                disabled={currPage === 1 ? true : false}
                                                onClick={firstPage}
                                            />
                                            <Pagination.Prev
                                                type="button"
                                                variant="outline-info"
                                                disabled={currPage === 1 ? true : false}
                                                onClick={prevPage}
                                            />
                                            <Pagination.Item
                                                //className={"page-num"}
                                                //name="currentPage"
                                                //value={currPage}
                                                //onChange={changePage}
                                                disabled
                                            >
                                                {currPage}
                                            </Pagination.Item>

                                            <Pagination.Next
                                                type="button"
                                                variant="outline-info"
                                                disabled={currPage === totalBikePages ? true : false}
                                                onClick={nextPage}
                                            />
                                            {/* {totalRentalPages.map(x=> <Pagination.Item key={x.id}>1</Pagination.Item>)} */}
                                            <Pagination.Last
                                                type="button"
                                                variant="outline-info"
                                                disabled={currPage === totalBikePages ? true : false}
                                                onClick={lastPage}
                                            />
                                        </Pagination>
                                    </div> </> : null}
                        </>
                    </div>
                </TableContainer>
            </div>
        </div>
    )
}