import React, { useEffect, useState } from "react";
import { useParams, Redirect } from "react-router";
import { Button, Typography } from "@material-ui/core";
import {
  UpdatesProvider,
  useUpdatesContext,
} from "../../Contexts/UpdatesContext";
import { useUserContext } from "../../Contexts/UserContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import CarSelection from "../../Cars/CarSelection";
import useStyles from "../../useStyles";
import { tsLocalDateTimeString } from "../../../utils/dates";

const MainForm = () => {
  const { packageid } = useParams();
  const { getPackages, createCarUpdates, packages, busy } = useUpdatesContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();
  const { setMessage, setTitle } = useStatusContext();
  const [packageName, setPackageName] = useState("");
  const [version, setVersion] = useState("");
  const [description, setDescription] = useState("");
  const [createDate, setCreateDate] = useState("");
  const [selectedVehicles, setSelectedVehicles] = useState([]);
  const [redirect, setRedirect] = useState("");
  const classes = useStyles();

  const onSubmit = async (event) => {
    try {
      event.preventDefault();
      const data = {
        package_id: parseInt(packageid),
        vins: selectedVehicles,
      };
      await createCarUpdates(data, token);
      setMessage(
        `Deployed ${packageName} ${version} to ${selectedVehicles.length} cars`
      );
      setRedirect(`/carupdate-status/${packageid}`);
    } catch (e) {
      setMessage(e.message);
    }
  };
  const getData = async () => {
    try {
      getPackages({ id: parseInt(packageid) }, token);
    } catch (e) {
      setMessage(e.message);
    }
  };

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

  useEffect(() => {
    setTitle(`Deploy ${packageName} ${version}`);
    // eslint-disable-next-line
  }, [packageName, version]);

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

    setPackageName(data.package_name);
    setVersion(data.version);
    setDescription(data.desc || "");
    setCreateDate(tsLocalDateTimeString(data.timestamp));
  }, [packages]);

  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}. {description}
        </Typography>
        <hr style={{ marginBottom: 30, marginTop: 30 }} />
        <CarSelection onSelection={setSelectedVehicles} />
        <Button
          type="submit"
          disabled={busy}
          fullWidth
          variant="contained"
          color="primary"
          className={classes.submit}
          onClick={onSubmit}
        >
          {busy ? "Deploying..." : "Deploy"}
        </Button>
      </form>
    </div>
  );
};

const UpdatePackageDeployForm = () => (
  <UpdatesProvider>
    <MainForm />
  </UpdatesProvider>
);

export default UpdatePackageDeployForm;
