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 Button from '@mui/material/Button';
import Pagination from 'react-bootstrap/Pagination'

export default function RentalList() {
    const [listOfRentals, setListOfRentals] = useState([]);
    const [page] = React.useState(0);
    const [rowsPerPage] = React.useState(4);
    const [currPage, setCurrPage] = React.useState(1);
    const [totalRentalPages, setRentalTotalPages] = useState();
    const [totalRentalElements, setTotalRentalElements] = useState();
    const [sortToggle, setSortToggle] = useState(true);
    let sortDirection = sortToggle
    let sortField = "id";
    const [sortToggle3, setSortToggle3] = useState(true);
    const [sortToggle0, setSortToggle0] = useState(true);
    //const [sortToggle4, setSortToggle4] = useState(true);
    const [sortToggle5, setSortToggle5] = useState(true);
    const [searchText, setSearchText] = useState("");

    let navigate = useNavigate();

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

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


    const handleSearch = () => {
        let sortDir = sortDirection ? "asc" : "desc";

        //axios.get(`/api/admin/rentals/search/${searchText}?page=${currPage-1}&size=${rowsPerPage}`, {
        axios.get(`/api/admin/rentals/search/${searchText}?pageNumber=${currPage - 1}&pageSize=${rowsPerPage}&sortBy=${sortField}&sortDir=${sortDir}`, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            console.log(response.data)
            setListOfRentals(response.data.content);
            setRentalTotalPages(response.data.totalPages);
            setTotalRentalElements(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/rentals/search/${searchText}?page=${currPage-1}&size=${rowsPerPage}`, {
        axios.get(`/api/admin/rentals/search/${searchText}?pageNumber=${currPage - 1}&pageSize=${rowsPerPage}&sortBy=${sortField}&sortDir=${sortDir}`, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            console.log(response.data)
            setListOfRentals(response.data.content);
            setRentalTotalPages(response.data.totalPages);
            setTotalRentalElements(response.data.totalElements);
            setCurrPage(response.data.number + 1);
            console.log(currPage);
            setSearchText(searchText);
            console.log(searchText);
        });
    }

    const editRental = (id) => {
        navigate(`/admin/rentals/update/${id}`);
    };

    const sortData0 = () => {
        if (sortToggle0 === true) {
            setSortToggle0(false);
            sortDirection = false;
        } else {
            setSortToggle0(true);
            sortDirection = true;
        }
        if (searchText) {
            updateHandleSearch(currPage);
        } else {
            updateTable(currPage);
        }
    }

    const sortData1 = () => {
        sortField = "id";
        if (sortToggle === true) {
            setSortToggle(false);
            sortDirection = false;
        } else {
            setSortToggle(true);
            sortDirection = true;
        }
        if (searchText) {
            updateHandleSearch(currPage);
        } else {
            updateTable(currPage);
        }
    }

    const sortData2 = () => {
        sortField = "endTime";
        if (sortToggle === true) {
            setSortToggle(false);
            sortDirection = false;
        } else {
            setSortToggle(true);
            sortDirection = true;
        }
        if (searchText) {
            updateHandleSearch(currPage);
        } else {
            updateTable(currPage);
        }
    }

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


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


    const sortData5 = () => {
        sortField = "discountEarned";
        if (sortToggle5 === true) {
            setSortToggle5(false);
            sortDirection = false;
        } else {
            setSortToggle5(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(totalRentalElements / rowsPerPage);
        if (currPage < condition) {
            setCurrPage(condition);
            if (searchText) {
                updateHandleSearch(condition);
            } else {
                updateTable(condition);
            }
        }
    };

    const nextPage = () => {
        let thisPage = currPage;
        if (
            currPage <
            Math.ceil(totalRentalElements / rowsPerPage)
        ) {
            console.log(totalRentalElements);
            console.log(Math.ceil(totalRentalElements / 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);

    }

    function createData(id, startTime, endTime, UserUsername, bikeSerialNumber, startStation, endStation, overageMin, discountEarned) {
        return { id, startTime, endTime, UserUsername, bikeSerialNumber, startStation, endStation, overageMin, discountEarned };
    }

    const rows = listOfRentals.map((value) => (
        createData(value.id, value.startTime, (value.endTime ? value.endTime : " "), value.user.username, value.bike.serialNumber, (value.startStation ? (value.startStation.name) : "Not Stationed"), (value.endStation ? (value.endStation.name) : "Not Stationed"), value.overageMinutes, (value.discountEarned? (value.discountEarned/100) : "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);

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

                </div>
            </div>
            <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 Rentals</h1>
                    <Table className='shadow-sm mb-3' sx={{ minWidth: 850 }} aria-label="simple table">
                        <TableHead className='shadow-sm'>
                            <TableRow>
                                <TableCell align="right" onClick={sortData0}>ID{" "}<span className={sortToggle0 ? "arrow arrow-down" : "arrow arrow-up"}> {" "} </span></TableCell>
                                <TableCell align="right" onClick={sortData1} >Start Time{" "}<span className={sortToggle ? "arrow arrow-down" : "arrow arrow-up"}> {" "} </span></TableCell>
                                <TableCell align="right" onClick={sortData2} >End Time{" "}<span className={sortToggle ? "arrow arrow-down" : "arrow arrow-up"}> {" "} </span></TableCell>
                                <TableCell align="right">Username</TableCell>
                                <TableCell align="right" onClick={sortData3} >Bike{" "}<span className={sortToggle3 ? "arrow arrow-down" : "arrow arrow-up"}> {" "} </span></TableCell>
                                <TableCell align="right">Start Station</TableCell>
                                <TableCell align="right">End Station</TableCell>
                                <TableCell align="right" >Time Overage </TableCell>
                                <TableCell align="center">Actions</TableCell>
                                <TableCell align="right" onClick={sortData5}> Discount Earned {" "}<span className={sortToggle5 ? "arrow arrow-down" : "arrow arrow-up"}> {" "} </span></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.startTime}</TableCell>
                                    <TableCell align="right">{row.endTime}</TableCell>
                                    <TableCell align="right">{row.UserUsername}</TableCell>
                                    <TableCell align="right">{row.bikeSerialNumber}</TableCell>
                                    <TableCell align="right">{row.startStation}</TableCell>
                                    <TableCell align="right" text-color="red">{row.endStation}</TableCell>
                                    <TableCell align="right"
                                        style={row.overageMin > 0 ? { color: "red" } : { color: "green" }}
                                    >{row.overageMin}{" minute(s)"}</TableCell>
                                    
                                    {/* {row.StationName !== null && (<TableCell align="right">{row.StationName}</TableCell>)} */}
                                    <TableCell align="right">
                                        <Button className="bg-secondary text-white mx-2" onClick={() => { editRental(row.id) }}>Edit!</Button>
                                        {/* <Button className="bg-danger text-white" onClick={() => { deleteRental(row.id) }}>Delete</Button> */}
                                    </TableCell>
                                    <TableCell align="right">${row.discountEarned}</TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                    <div className='d-flex flex-wrap justify-content-between'>
                        {/* <Button
                        className="bg-info text-white m-2 align-middle"
                        onClick={addRental}
                    >
                        Add Rental
                    </Button> */}
                        {/* <TablePagination
                        rowsPerPageOptions={[5, 10, 25]}
                        component="div"
                        count={rows.length}
                        rowsPerPage={rowsPerPage}
                        page={page}
                        onPageChange={handleChangePage}
                        onRowsPerPageChange={handleChangeRowsPerPage}
                    ></TablePagination> */}
                    </div>
                    <>
                        {listOfRentals.length > 0 ?
                            <>
                                <div style={{ float: "left", marginLeft: "5px" }}>
                                    Showing Page {currPage} of {totalRentalPages}
                                </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 === totalRentalPages ? true : false}
                                            onClick={nextPage}
                                        />
                                        {/* {totalRentalPages.map(x=> <Pagination.Item key={x.id}>1</Pagination.Item>)} */}
                                        <Pagination.Last
                                            type="button"
                                            variant="outline-info"
                                            disabled={currPage === totalRentalPages ? true : false}
                                            onClick={lastPage}
                                        />
                                    </Pagination>
                                </div> </> : null}
                    </>
                </TableContainer>
            </div>
        </div>
    )
}