import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { Grid, TextField } from "@material-ui/core";

import CarUpdateStatusProgress from "../../Controls/CarUpdateStatusProgress";
import CarUpdateStatusTable from "../../Controls/CarUpdateStatusTable";
import {
  CarUpdatesProvider,
  useCarUpdatesContext,
} from "../../Contexts/CarUpdatesContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import useStyles from "../../useStyles";
import { useUserContext } from "../../Contexts/UserContext";
import { logger } from "../../../services/monitoring";
import { LocalDateTimeString } from "../../../utils/dates";

const MainForm = () => {
  const { vin, carupdateid } = useParams();
  const [manifest, setManifest] = useState(null);
  const [status, setStatus] = useState(null);
  const { setTitle, setSitePath, setMessage } = useStatusContext();
  const { getCarUpdates, carUpdates } = useCarUpdatesContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();
  const classes = useStyles();

  useEffect(() => {
    (async () => {
      try {
        const result = await getCarUpdates({ id: carupdateid }, token);
        if (!result.data && result.data.length === 0)
          throw new Error(`error getting update ${carupdateid}`);
        setManifest(result.data[0]["updatemanifest"]);
      } catch (e) {
        setMessage(e.message);
      }
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (!manifest) return;
    const title = `Vehicle ${vin}, Update ${manifest.name}`;
    setTitle(title);
    setSitePath([
      {
        label: "Vehicles",
        link: "/vehicles",
      },
      {
        label: `Vehicle ${vin} Details`,
        link: `/vehicle-status/${vin}`,
      },
      {
        label: `Manifest ${manifest.id} Details`,
        link: `/package-status/${manifest.id}`,
      },
      {
        label: title,
      },
    ]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [manifest]);

  useEffect(() => {
    try {
      if (carUpdates.length === 0) return;
      setStatus(carUpdates[0]);
    } catch (e) {
      setMessage(e.message);
      logger.warn(e.stack);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [carUpdates]);

  if (!status) return null;

  return (
    <div className={classes.root}>
      <Grid container spacing={2}>
        {manifest && (
          <>
            <Grid item md={4} className={classes.textJustifyAlign}>
              <TextField
                label="Name"
                defaultValue={manifest.name}
                className={classes.fullWidth}
                InputProps={{
                  readOnly: true,
                }}
              />
            </Grid>
            <Grid item md={4} className={classes.textCenterAlign}>
              <TextField
                label="Version"
                defaultValue={manifest.version}
                className={classes.fullWidth}
                InputProps={{
                  readOnly: true,
                }}
              />
            </Grid>
            <Grid item md={4} className={classes.textRightAlign}>
              <TextField
                label="Created"
                defaultValue={LocalDateTimeString(manifest.created)}
                className={classes.fullWidth}
                InputProps={{
                  readOnly: true,
                }}
              />
            </Grid>
            <Grid item md={12}>
              <TextField
                label="Description"
                defaultValue={manifest.description}
                className={classes.fullWidth}
                InputProps={{
                  readOnly: true,
                }}
              />
            </Grid>
          </>
        )}
        <Grid item md={12}>
          <CarUpdateStatusProgress status={status} classes={classes} />
        </Grid>
        <Grid item md={12}>
          <CarUpdateStatusTable carupdateid={carupdateid} token={token} />
        </Grid>
      </Grid>
    </div>
  );
};

const UpdateStatus = () => (
  <CarUpdatesProvider>
    <MainForm />
  </CarUpdatesProvider>
);

export default UpdateStatus;
