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

import useStyles from "../../useStyles";
import DigitalTwin from "../../DigitalTwin";
import {
  useVehicleContext,
  VehicleProvider,
} from "../../Contexts/VehicleContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import { useUserContext } from "../../Contexts/UserContext";
import { logger } from "../../../services/monitoring";

const Main = (props) => {
  const { getState } = useVehicleContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();
  const { setMessage } = useStatusContext();
  const classes = useStyles();
  const [carState, setCarState] = useState(null);
  const { vin } = props;

  useEffect(() => {
    if (!vin) return;
    (async () => {
      try {
        const result = await getState(token, vin);
        setCarState(result.data);
      } catch (e) {
        setMessage(e.message);
        logger.warn(e.stack);
      }
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [vin]);

  return (
    <div className={clsx(classes.paper, classes.tableSize)}>
      <Typography variant="h6" style={{ paddingBottom: "10px" }}>
        Digital Twin
      </Typography>
      {carState && (
        <>
          <div>
            <b>Connected</b>: {carState.online.toString()}
          </div>
          <div>
            <b>ICC Connected</b>: {carState?.online_hmi.toString()}
          </div>
          <DigitalTwin {...carState} />
        </>
      )}
    </div>
  );
};

const DigitalTwinTab = (props) => (
  <VehicleProvider>
    <Main {...props} />
  </VehicleProvider>
);

export default DigitalTwinTab;
