import React, { useEffect, useState } from "react";
import { useParams, Redirect } from "react-router";
import { Button, Grid, Typography } from "@material-ui/core";
import clsx from "clsx";

import {
  ManifestsProvider,
  useManifestsContext,
} from "../../Contexts/ManifestsContext";
import {
  CarUpdatesProvider,
  useCarUpdatesContext,
} from "../../Contexts/CarUpdatesContext";
import { VehicleProvider } from "../../Contexts/VehicleContext";
import { useUserContext } from "../../Contexts/UserContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import useStyles from "../../useStyles";
import SearchField from "../../Controls/SearchField";
import
  CarSelectionTable from "../../Controls/CarSelectionTable";
import { logger } from "../../../services/monitoring";
import { LocalDateTimeString } from "../../../utils/dates";
import {FleetProvider} from "../../Contexts/FleetContext";

const MainForm = () => {
  const { manifest_id } = useParams();
  const { getManifests, manifests, busy } = useManifestsContext();
  const { deployCarUpdates } = useCarUpdatesContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();
  const { setMessage, setTitle, setSitePath } = useStatusContext();
  const [manifestName, setManifestName] = useState("");
  const [version, setVersion] = useState("");
  const [createDate, setCreateDate] = useState("");
  const [selected, setSelected] = useState([]);
  const [search, setSearch] = useState("");
  const [redirect, setRedirect] = useState("");
  const classes = useStyles();

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

  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);
    }
  };

  const onSubmit = async (event) => {
    try {
      event.preventDefault();
      const data = {
        manifest_id: parseInt(manifest_id),
        vins: selected,
      };
      await deployCarUpdates(data, token);
      setMessage(
        `Deployed ${manifestName} ${version} to ${selected.length} cars`
      );
      setRedirect(`/package-status/${manifest_id}`);
    } catch (e) {
      setMessage(e.message);
      logger.warn(e.stack);
    }
  };

  const getData = async () => {
    try {
      getManifests({ id: parseInt(manifest_id) }, token);
    } catch (e) {
      setMessage(e.message);
      logger.warn(e.stack);
    }
  };

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

  useEffect(() => {
    const title = `Deploy ${manifestName} ${version}`;
    setTitle(title);
    setSitePath([
      {
        label: "Deployments",
        link: "/packages",
      },
      {
        label: title,
      },
    ]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [manifestName, version]);

  useEffect(() => {
    if (!manifests || manifests.length === 0) return;
    const data = manifests[0];

    setManifestName(data.name);
    setVersion(data.version);
    setCreateDate(LocalDateTimeString(data.created));
  }, [manifests]);

  if (redirect.length > 0) {
    return <Redirect to={redirect} />;
  }

  return (
    <div className={classes.paper}>
      <form className={classes.form} noValidate action="{onSubmit}">
        <Typography variant="body2">Created {createDate}.</Typography>
        <Grid container className={classes.root} spacing={2}>
          <Grid item md={4}>
            <div
              className={classes.labelInline}
            >{`${selected.length} Selected`}</div>
          </Grid>
          <Grid item md={4} className={classes.textCenterAlign}>
            <SearchField classes={classes} onSearch={handleSearch} />
          </Grid>
          <Grid item md={4} className={classes.textRightAlign}>
            <Button
              type="submit"
              disabled={busy || selected.length === 0}
              variant="contained"
              color="primary"
              className={clsx(classes.formControl, classes.textField)}
              onClick={onSubmit}
            >
              {busy ? "Deploying..." : "Deploy"}
            </Button>
          </Grid>
        </Grid>
        <CarSelectionTable
          classes={classes}
          token={token}
          multiSelect={true}
          search={{ search }}
          selected={selected}
          onSelect={handleSelect}
          onSelectAll={handleSelectAll}
        />
      </form>
    </div>
  );
};

const FleetDeployForm = () => (
  <FleetProvider>
    <ManifestsProvider>
      <CarUpdatesProvider>
        <MainForm />
      </CarUpdatesProvider>
    </ManifestsProvider>
  </FleetProvider>
);

export default FleetDeployForm;
