import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import {
  Table,
  TableBody,
  TableCell,
  TableFooter,
  TablePagination,
  TableRow,
  Toolbar,
} from "@material-ui/core";

import {
  useVehicleContext,
  VehicleProvider,
} from "../../Contexts/VehicleContext";
import { useUserContext } from "../../Contexts/UserContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import useStyles from "../../useStyles";
import { LocalDateTimeString } from "../../../utils/dates";
import TableHeaderSortable from "../../Table/HeaderSortable";
import SearchField from "../../Controls/SearchField";
import { logger } from "../../../services/monitoring";

const tableColumns = [
  {
    id: "vin",
    label: "VIN",
  },
  {
    id: "model",
    label: "Model",
  },
  {
    id: "year",
    label: "Year",
  },
  {
    id: "trim",
    label: "Trim",
  },
  {
    id: "created_at",
    label: "Created",
  },
  {
    id: "updated_at",
    label: "Updated",
  },
];

const MainForm = () => {
  const classes = useStyles();
  const [pageSize, setPageSize] = useState(10);
  const [pageIndex, setPageIndex] = useState(0);
  const [orderBy, setOrderBy] = useState("vin");
  const [order, setOrder] = useState("asc");
  const [search, setSearch] = useState("");
  const { getVehicles, vehicles, totalVehicles } = useVehicleContext();
  const { setMessage, setTitle } = useStatusContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();

  const sortHandler = (event, property) => {
    if (property === orderBy) {
      if (order === "asc") {
        setOrder("desc");
      } else {
        setOrder("asc");
      }
    } else {
      setOrderBy(property);
      setOrder("asc");
    }
  };

  useEffect(() => {
    setTitle("Vehicles");
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

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

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

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

  const handleSearch = (search) => {
    setSearch(search);
  };

  return (
    <div className={classes.paper} style={{ height: 700, width: "100%" }}>
      <Toolbar className={classes.tableToolbar}>
        <SearchField classes={classes} onSearch={handleSearch} />
      </Toolbar>
      <Table>
        <TableHeaderSortable
          classes={classes}
          orderBy={orderBy}
          order={order}
          columnData={tableColumns}
          onSortRequest={sortHandler}
        />
        <TableBody>
          {vehicles.map((row) => (
            <TableRow key={row.vin}>
              <TableCell align="center">
                <Link to={`/vehicle-status/${row.vin}`}>{row.vin}</Link>
              </TableCell>
              <TableCell align="center">{row.model}</TableCell>
              <TableCell align="center">{row.year}</TableCell>
              <TableCell align="center">{row.trim || ""}</TableCell>
              <TableCell align="center">
                {LocalDateTimeString(row.created)}
              </TableCell>
              <TableCell align="center">
                {LocalDateTimeString(row.updated)}
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
        <TableFooter>
          <TableRow>
            <TablePagination
              rowsPerPageOptions={[5, 10, 25, 100]}
              colSpan={6}
              count={totalVehicles}
              rowsPerPage={pageSize}
              page={pageIndex}
              SelectProps={{
                inputProps: { "aria-label": "rows per page" },
                native: true,
              }}
              onChangePage={handleChangePageIndex}
              onChangeRowsPerPage={handleChangePageSize}
            />
          </TableRow>
        </TableFooter>
      </Table>
    </div>
  );
};

const VehiclesList = () => (
  <VehicleProvider>
    <MainForm />
  </VehicleProvider>
);

export default VehiclesList;
