import { useRef, useState, useEffect } from "react";
import { Link } from "react-router-dom";
import Chip from '@mui/material/Chip';
import Stack from '@mui/material/Stack';
import ConnectedIcon from "../Controls/ConnectedIcon";
import useStyles from "../useStyles";
import { useIntersectObserver } from "../../hooks";
import api from "../../services/vehiclesAPI";

// Prevent fetching missing data by not including `token` prop

export function VehicleTeaserController(props) {
  const el = useRef(null);
  const isVisible = useIntersectObserver(el, "0px", true);
  const [isMissingData, setIsMissingData] = useState(false);
  const [vehicle, setVehicle] = useState({});

  const classes = useStyles();

  useEffect(() => {
    if (props.trim === undefined) {
      setIsMissingData(true);
    }
  }, [isVisible, props.trim]);

  useEffect(() => {
    if (isVisible && props.token) {
      api.getVehicle(props.vin, props.token)
        .then(setVehicle)
        .catch(() => setVehicle({}));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isMissingData, isVisible, props.vin, props.token]);

  if (!props.vin) {
    return (
      <div className={classes.alignBaseline}>
        Missing VIN
      </div>
    );
  }

  return (
    <div ref={el}>
      <VehicleTeaser
        vin={props.vin}
        trex={props.trex}
        icc={props.icc}
        trim={props.trim || vehicle.trim}
      />
    </div>
  );
}

export function VehicleTeaser(props) {
  const classes = useStyles();

  return (
    <div className={classes.alignBaseline}>
      <ConnectedIcon
        connected={props.trex}
        connectedHMI={props.icc}
        style={{ display: "flex", marginRight: 3 }}
      />
      <Link to={`/vehicle-status/${props.vin}`}>
        {props.vin}
      </Link>
      <Stack direction="row" spacing={1} style={{ marginLeft: 3 }}>
        {props.trim && <Chip label={props.trim} size="small" />}
      </Stack>
    </div>
  )
}
