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

import { Permissions } from "../../../utils/roles";
import { useStatusContext } from "../../Contexts/StatusContext";
import { useUserContext } from "../../Contexts/UserContext";
import { VehicleProvider } from "../../Contexts/VehicleContext";
import CarSelectionTable from "../../Controls/CarSelectionTable";
import OptionsDropdown from "../../Controls/OptionsDropdown";
import { RoleWrap } from "../../Controls/RoleWrap";
import SearchField from "../../Controls/SearchField";
import BulkActions from "../../BulkActions";
import useQuery from "./useQuery";
import useStyles from "../../useStyles";

const MainForm = () => {
  const classes = useStyles();
  const [online, setOnline] = useState(null);
  const [onlineHMI, setOnlineHMI] = useState(null);
  const [selectedVins, setSelectedVins] = useState([]);
  const { payload, query, setQuery, loading } = useQuery();
  const { setTitle, setSitePath } = useStatusContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
    groups,
    providers,
  } = useUserContext();

  const handleSearch = (query) => {
    setQuery(query);
  };

  const handleOnline = (event) => {
    setOnline(event.target.checked || null);
  };

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

  const handleSelect = (event, key) => {
    setSelectedVins((selectedVins) => {
      if (event.target.checked) {
        return [...selectedVins, key];
      }
      return selectedVins.filter(vin => vin !== key);
    });
  };

  const handleOnlineHMI = (event) => {
    setOnlineHMI(event.target.checked || null);
  };

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

  return (
    <div className={clsx(classes.paper, classes.tableSize)}>
      <Grid container className={classes.root} spacing={2}>
        <Grid item md={4} className={clsx(classes.textJustifyAlign, classes.actionsBar)}>
          <RoleWrap
            groups={groups}
            providers={providers}
            rolesPerProvider={Permissions.FiskerCreate}
          >
            <Link to="/vehicle-add">
              <AddCircleIcon fontSize="large" />
            </Link>
          </RoleWrap>
          <BulkActions ids={selectedVins} actions={["addTags", "addToFleet", "updateConfig", "updateFleetVehicles"]} />
        </Grid>
        <Grid item md={4} className={classes.textCenterAlign}>
          <SearchField classes={classes} onSearch={handleSearch} savedSearchValue={query} />
        </Grid>
        <Grid item md={2} className={clsx(classes.textJustifyAlign, classes.actionsBar)}>
          <OptionsDropdown listId="filter-menu">
            <MenuItem>
              <FormControlLabel
                control={<Checkbox checked={online} onChange={handleOnline} />}
                label="Only online"
              />
            </MenuItem>
            <MenuItem>
              <FormControlLabel
                control={
                  <Checkbox checked={onlineHMI} onChange={handleOnlineHMI} />
                }
                label="Only online HMI"
              />
            </MenuItem>
          </OptionsDropdown>
        </Grid>
        <Grid item md={2} className={classes.textRightAlign} />
      </Grid>
      {!loading && <CarSelectionTable
        classes={classes}
        token={token}
        multiSelect
        search={{
          ...payload,
          online,
          online_hmi: onlineHMI,
        }}
        selected={selectedVins}
        onSelect={handleSelect}
        onSelectAll={handleSelectAll}
      />}
    </div>
  );
};

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

export default VehiclesList;
