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

import { useUserContext } from "../../Contexts/UserContext"
import { useStatusContext } from "../../Contexts/StatusContext";
import { FleetProvider } from "../../Contexts/FleetContext"
import { useLocalStorage } from "../../useLocalStorage";
import useStyles from "../../useStyles";
import SearchField from "../../Controls/SearchField";
import FleetSelectionTable from "../../Controls/FleetSelectionTable";


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

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

  useEffect(() => {
    setTitle("Fleets");
    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={classes.textJustifyAlign}>
          <Link to={"/fleet-add"}>
            <AddCircleIcon fontSize="large" />
          </Link>
        </Grid>
        <Grid item md={4} className={classes.textCenterAlign}>
          <SearchField classes={classes} onSearch={handleSearch} savedSearchValue={search} />
        </Grid>
        <Grid item md={4} className={classes.textRightAlign}></Grid>
      </Grid>
      <FleetSelectionTable
        token={token}
        classes={classes}
        search={{ search }}
        multiSelect={false}
      />
    </div>
  );
};

const FleetsTable = (props) => (
  <FleetProvider>
    <MainForm {...props} />
  </FleetProvider>
);

export default FleetsTable;
