import React from 'react';
import axios from 'axios';
import { useEffect, useState } from 'react';
//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 "../../App.css";
import Pagination from 'react-bootstrap/Pagination'
import { Navigate } from 'react-router-dom';


export default function UserDashboard() {
  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 [sortToggle5, setSortToggle5] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    axios.get(`/api/rental/history?pageNumber=${currPage - 1}&pageSize=${rowsPerPage}&sortBy=${sortField}&sortDir=asc`, {
      headers: {
        Authorization: 'Bearer ' + localStorage.getItem('accessToken')
      }
    }).then((response) => {
      setListOfRentals(response.data.content);
      setRentalTotalPages(response.data.totalPages);
      setTotalRentalElements(response.data.totalElements);
      setCurrPage(response.data.number + 1);
    })
      .catch((error) => {
        setError(error.response.data.error ?? error.response.data.message ?? "There was a problem");
      });
  }, [rowsPerPage, currPage]);



  const sortData0 = () => {
    sortField = "id";
    if (sortToggle0 === true) {
      setSortToggle0(false);
      sortDirection = false;
    } else {
      setSortToggle0(true);
      sortDirection = true;
    }
    updateTable(currPage);
  }

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

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

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


    const sortData5 = () => {
        sortField = "discountEarned";
        if (sortToggle5 === true) {
            setSortToggle5(false);
            sortDirection = false;
        } else {
            setSortToggle5(true);
            sortDirection = true;
        }
            updateTable(currPage);
    }

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


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

  const rows = listOfRentals.map((value) => (
    createData(value.id, value.startTime, (value.endTime ? value.endTime : " "), 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"))
  ))

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

  const prevPage = () => {
    let prevPage = 1;
    let thisPage = currPage;
    if (currPage > prevPage) {
      setCurrPage(currPage - 1);
      updateTable(thisPage - 1);
    }
  };

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

  const nextPage = () => {
    let thisPage = currPage;
    if (
      currPage <
      Math.ceil(totalRentalElements / rowsPerPage)
    ) {
      setCurrPage(currPage + 1);
      updateTable(thisPage + 1);
    }
  };

  const returnBike = () => {
    Navigate(`/stations/list`);
  }



  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'>My Rental History</h1>
          <span className="text-danger">{error}</span>
          <Table className='shadow-sm mb-3' sx={{ minWidth: 850 }} aria-label="simple table">
            <TableHead className='shadow-sm'>
              <>
                {listOfRentals.length > 0 ?
                  <>
                    <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" >Overage Time</TableCell>
                      <TableCell align="right" onClick={sortData5} > Discount Earned  {" "}<span className={sortToggle5 ? "arrow arrow-down" : "arrow arrow-up"}> {" "} </span></TableCell>

                      {/* <TableCell align="center" >Actions</TableCell> */}
                    </TableRow>
                  </>
                  : <>

                    <TableRow>
                      <TableCell align="center">
                        <h5>You have 0 records in your Rental History</h5>
                      </TableCell>
                    </TableRow>

                  </>}
              </>
            </TableHead>
            <TableBody>
              {rows.length > 0 ? 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">{row.endStation != "Not Stationed" ? row.endStation : <a className="btn btn-info shadow-sm" href={"/stations/list"}>Return Bike</a>}</TableCell>
                  <TableCell align="right"
                    style={row.overageMin > 0 ? { color: "red" } : { color: "green" }}
                  >{row.overageMin}{" minute(s)"}</TableCell>
                  <TableCell align="right">${row.discountEarned}</TableCell>
                  {/* {row.StationName !== null && (<TableCell align="right">{row.StationName}</TableCell>)} */}
                  {/* <TableCell align="right"> */}
                  {/* <Button className="bg-danger text-white" onClick={() => { deleteRental(row.id) }}>Delete</Button> */}
                  {/* </TableCell> */}
                </TableRow>
              )) : (<div className="text-info">No rentals found</div>)}
            </TableBody>
          </Table>
          <div className='d-flex flex-wrap justify-content-between'>
          </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
                      disabled
                    >
                      {currPage}
                    </Pagination.Item>

                    <Pagination.Next
                      type="button"
                      variant="outline-info"
                      disabled={currPage === totalRentalPages ? true : false}
                      onClick={nextPage}
                    />
                    <Pagination.Last
                      type="button"
                      variant="outline-info"
                      disabled={currPage === totalRentalPages ? true : false}
                      onClick={lastPage}
                    />
                  </Pagination>
                </div> </> : null}
          </>
        </TableContainer>
      </div>
    </div>

  )
}
