import {
  Typography,
  Grid,
  FormControlLabel,
  Checkbox,
} from "@material-ui/core";
import clsx from "clsx";
import React, { useState } from "react";

import { useUserContext } from "../../Contexts/UserContext";
import { VehicleProvider } from "../../Contexts/VehicleContext";
import { useLocalStorage } from "../../useLocalStorage";
import CarECUsTable from "../../Controls/CarECUsTable";
import SearchField from "../../Controls/SearchField";
import useStyles from "../../useStyles";

const MainForm = ({ vin }) => {
  const [search, setSearch] = useLocalStorage("ECU_SEARCH", "");
  const [unique, setUnique] = useState(true);
  const classes = useStyles();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();

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

  const handleUnique = () => {
    setUnique(unique => !unique);
  }

  return (
    <div className={clsx(classes.tableSize, classes.textCenterAlign)}>
      <Typography variant="h6" className={classes.labelInline}>
        Car ECUs
      </Typography>
      <Grid
        container
        className={classes.textCenterAlign}
        spacing={2}
        justifyContent="center"
      >
        <Grid item md={5} className={clsx(classes.textCenterAlign, classes.flex)}>
          <SearchField classes={classes} onSearch={handleSearch} savedSearchValue={search} />
          <FormControlLabel
            label="Current ECUs"
            control={<Checkbox checked={unique} onChange={handleUnique} />}
            className={classes.noWrap}
          />
        </Grid>
      </Grid>
      <CarECUsTable vin={vin} token={token} classes={classes} search={search} unique={unique} />
    </div>
  );
};

const CarUpdatesTab = ({ vin }) => (
  <VehicleProvider>
    <MainForm vin={vin} />
  </VehicleProvider>
);

export default CarUpdatesTab;
