import React, { useEffect, useState } from "react";
import { Grid } from "@material-ui/core";
import AddCircleIcon from "@material-ui/icons/AddCircle";
import { Link } from "react-router-dom";

import { VehicleProvider } from "../../Contexts/VehicleContext";
import { useUserContext } from "../../Contexts/UserContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import useStyles from "../../useStyles";
import SendCommand from "../SendCommand";
import SearchField from "../../Controls/SearchField";
import CarSelectionTable from "../CarSelectionTable";
import { logger } from "../../../services/monitoring";

const MainForm = () => {
  const classes = useStyles();
  const [selected, setSelected] = useState([]);
  const [search, setSearch] = useState("");
  const { setTitle, setSitePath } = useStatusContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();

  const handleSearch = (search) => {
    setSelected([]);
    setSearch(search);
  };

  const handleSelectAll = (cars) => {
    setSelected(cars);
  };

  const handleSelect = (event, key) => {
    try {
      let newSelected;
      if (event.target.checked) {
        newSelected = [...selected];
        newSelected.push(key);
      } else {
        newSelected = selected.filter((vin) => vin !== key);
      }
      setSelected(newSelected);
    } catch (e) {
      logger.warn(e.stack);
    }
  };

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

  return (
    <div className={classes.paper} style={{ height: 700, width: "100%" }}>
      <Grid container className={classes.root} spacing={2}>
        <Grid item md={6}>
          <Link to="/vehicle-add" className={classes.labelInline}>
            <AddCircleIcon fontSize="large" />
          </Link>
          <SearchField classes={classes} onSearch={handleSearch} />
          <div
            className={classes.labelInline}
          >{`${selected.length} Selected`}</div>
        </Grid>
        <Grid item md={6} style={{ textAlign: "right" }}>
          <SendCommand vins={selected} style={{ display: "flex" }} />
        </Grid>
      </Grid>
      <CarSelectionTable
        classes={classes}
        token={token}
        search={{ search }}
        selected={selected}
        onSelect={handleSelect}
        onSelectAll={handleSelectAll}
      />
    </div>
  );
};

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

export default VehiclesList;
