import { Grid, Tooltip } from "@material-ui/core";
import DeleteIcon from "@material-ui/icons/Delete";
import EditIcon from "@material-ui/icons/Edit";
import clsx from "clsx";
import React, { useEffect, useState } from "react";
import { Redirect } from "react-router";
import { Link } from "react-router-dom";

import { logger } from "../../../../services/monitoring";
import { Permissions } from "../../../../utils/roles";
import { useStatusContext } from "../../../Contexts/StatusContext";
import { useUserContext } from "../../../Contexts/UserContext";
import {
  useVehicleContext,
  VehicleProvider
} from "../../../Contexts/VehicleContext";
import { RoleWrap } from "../../../Controls/RoleWrap";
import DeleteConfirmation from "../../../DeleteConfirmation";
import useStyles from "../../../useStyles";

const MainForm = ({ vin }) => {
  const classes = useStyles();
  const { setMessage } = useStatusContext();
  const { vehicle, getVehicle, deleteVehicle } = useVehicleContext();
  const [redirect, setRedirect] = useState(null);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const {
    token: {
      idToken: { jwtToken: token },
    },
    groups,
    providers,
  } = useUserContext();

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

  const onDelete = async () => {
    try {
      await deleteVehicle(vin, token);
      setMessage(`Deleted ${vin}`);
      setRedirect(`/vehicles`);
    } catch (e) {
      setMessage(e.message);
      logger.warn(e.stack);
    }
  };

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

  return (
    <div className={clsx(classes.paper, classes.tableSize)}>
      <Grid container className={classes.root} spacing={2}>
        <Grid item md={12} className={classes.textCenterAlign}>
          <p>
            <b>VIN</b>: {vin}
          </p>
          {vehicle.log_level != null && (
            <p>
              <b>Log Level</b>: {vehicle.log_level}
            </p>
          )}
        </Grid>
        {vehicle.canbus && (
          <Grid item md={12} className={classes.textCenterAlign}>
            <b>CANBus</b>
            <p>
              <b>Enabled</b>: {vehicle.canbus.enabled.toString()}
            </p>
            <p>
              <b>Max Memory Buffer Size</b>: {vehicle.canbus.max_mem_buffer_size ?? "Default"}
            </p>
            <p>
              <b>Enabled</b>: {vehicle.canbus.data_logger_enabled.toString()}
            </p>
            <p>
              <b>Max Disk Buffer Size</b>: {vehicle.canbus.max_disk_buffer_size ?? "Default"}
            </p>
            <p>
              <b>Filters</b>: {vehicle.canbus.filters ? vehicle.canbus.filters.length : 0}
            </p>
          </Grid>
        )}
        <Grid item md={12} className={classes.textCenterAlign}>
          <RoleWrap
            groups={groups}
            providers={providers}
            rolesPerProvider={Permissions.FiskerCreate}
          >
            <Tooltip key={`update-${vin}`} title={`Update "${vin}"`}>
              <Link to={`/vehicle-update?vin=${vin}`} style={{ margin: 5 }}>
                <EditIcon aria-label={`Update "${vin}"`} />
              </Link>
            </Tooltip>
          </RoleWrap>
          <RoleWrap
            groups={groups}
            providers={providers}
            rolesPerProvider={Permissions.FiskerDelete}
          >
            <Tooltip key={`delete-${vin}`} title={`Delete "${vin}"`}>
              <Link to="#" onClick={() => setShowDeleteModal(true)}>
                <DeleteIcon aria-label={`Delete "${vin}"`} />
              </Link>
            </Tooltip>
          </RoleWrap>
        </Grid>
      </Grid>
      <DeleteConfirmation
        message={vin}
        open={showDeleteModal}
        close={() => setShowDeleteModal(false)}
        deleteFunction={onDelete}
      />
    </div>
  );
};

const CarDetails = (props) => (
  <VehicleProvider>
    <MainForm {...props} />
  </VehicleProvider>
);

export default CarDetails;
