import useStyles from "../../useStyles";
import clsx from "clsx";
import {Grid, Table, TableBody, TableCell, TableFooter, TablePagination, TableRow, Typography} from "@material-ui/core";
import React, {useEffect, useState} from "react";
import {useVehicleContext, VehicleProvider} from "../../Contexts/VehicleContext";
import SearchField from "../../Controls/SearchField";
import {useLocalStorage} from "../../useLocalStorage";
import {useStatusContext} from "../../Contexts/StatusContext";
import {useUserContext} from "../../Contexts/UserContext";
import {logger} from "../../../services/monitoring";
import TableHeaderSortable from "../../Table/HeaderSortable";
import {Link} from "react-router-dom";

const PAGE_SIZE = "VEHICLE_FLEETS_TABLE_PAGE_SIZE";

const tableColumns = [
  {
    id: "fleet",
    label: "CAN ID"
  },
];

const MainForm = (props) => {
  const classes = useStyles();
  const {vin} = props;

  const [search, onSearch] = useState("");
  const [pageSize, setPageSize] = useLocalStorage(PAGE_SIZE, 10);
  const [pageIndex, setPageIndex] = useState(0);
  const [orderBy, setOrderBy] = useState("id");
  const [order, setOrder] = useState("desc");
  const {setMessage} = useStatusContext();
  const {token: {idToken: {jwtToken: token}}} = useUserContext();
  const {getFleets, fleets, totalFleets} = useVehicleContext();

  useEffect(() => {
    (async () => {
      try {
        if (!vin || !token) return;
        await getFleets(
          vin,
          {
            search,
            limit: pageSize,
            offset: pageSize * pageIndex,
            order: `${orderBy} ${order}`,
          },
          token
        );
      } catch (e) {
        setMessage(e.message);
        logger.warn(e.stack);
      }
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [vin, token, pageIndex, pageSize, orderBy, order, search]);

  const handleChangePageIndex = (event, newIndex) => {
    setPageIndex(newIndex);
  };

  const handleChangePageSize = (event) => {
    setPageSize(parseInt(event.target.value, 10));
    setPageIndex(0);
  };

  const handleSort = (event, property) => {
    try {
      if (property === orderBy) {
        if (order === "asc") {
          setOrder("desc");
        } else {
          setOrder("asc");
        }
      } else {
        setOrderBy(property);
        setOrder("asc");
      }
    } catch (e) {
      logger.warn(e.stack);
    }
  };

  return (
    <div className={clsx(classes.paper, classes.tableSize)}>
      <Typography variant="h6">Fleets</Typography>
      <Grid container className={classes.textCenterAlign} spacing={2} justifyContent="center">
        <Grid item md={3} className={classes.textCenterAlign}>
          <SearchField classes={classes} onSearch={onSearch}/>
        </Grid>
      </Grid>
      <Table style={{width:"auto"}}>
        <TableHeaderSortable
          classes={classes}
          orderBy={orderBy}
          order={order}
          columnData={tableColumns}
          onSortRequest={handleSort}
        />
        <TableBody>
          {fleets.map((row) => (
            <TableRow key={row} width="200px">
              <TableCell align="center">
                <Link to={`/fleet/${row}`}>{row}</Link>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
        <TableFooter>
          <TableRow>
            <TablePagination
              rowsPerPageOptions={[5, 10, 25, 100]}
              colSpan={8}
              count={totalFleets}
              rowsPerPage={pageSize}
              page={pageIndex}
              SelectProps={{
                inputProps: {"aria-label": "rows per page"},
                native: true,
              }}
              onPageChange={handleChangePageIndex}
              onRowsPerPageChange={handleChangePageSize}
            />
          </TableRow>
        </TableFooter>
      </Table>
    </div>
  )
}

const FleetsTab = (props) => {
  return (
    <VehicleProvider>
      <MainForm {...props}/>
    </VehicleProvider>
  )
}


export default FleetsTab;