import { Box, Checkbox, FormControlLabel, Grid, Tooltip } from "@material-ui/core";
import EditIcon from "@material-ui/icons/Edit";
import UploadIcon from '@mui/icons-material/Upload';
import clsx from "clsx";
import React, { useEffect, useState } from "react";
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 GeneralConfirmation from "../../../GeneralConfirmation";
import useStyles from "../../../useStyles";

const MainForm = ({ vin }) => {
  const classes = useStyles();
  const { setMessage } = useStatusContext();
  const { vehicle, getVehicle, uploadConfig } = useVehicleContext();
  const [showUploadConfigModal, setShowUploadConfigModal] = useState(false);
  const [forced, setForced] = useState(false);
  const {
    token: {
      idToken: { jwtToken: token },
    },
    groups,
    providers,
  } = useUserContext();

  const showDebugMask = (process.env.REACT_APP_ENABLE_DEBUGMASK === "1");

  const onForcedChange = (event) => {
    setForced(event.target.checked);
  }

  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 onUploadConfig = async () => {
    try {
      await uploadConfig(vin, forced, token);
      setMessage(`Config Uploaded ${vin}`);
    } catch (e) {
      setMessage(e.message);
      logger.warn(e.stack);
    }
  }

  const findDLTLevelStr = (dltLevelNum) => {
    switch (dltLevelNum) {
      case 0:
        return "Off"
      case 1:
        return "Fatal"
      case 2:
        return "Error"
      case 3:
        return "Warn"
      case 4:
        return "Info"
      case 5:
        return "Debug"
      case 6:
        return "Verbose"
      case 255:
        return "Delete"
      default:
        return "Default"
    }
  }

  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>
          <p>
            <b>ICCID</b>: {vehicle.iccid}
          </p>
          <p>
            <b>Version</b>: {vehicle.os_version} / {vehicle.sums_version}
          </p>
          <p>
            <b>Model</b>: {vehicle.model}
          </p>
          <p>
            <b>Year</b>: {vehicle.year}
          </p>
          <p>
            <b>Trim</b>: {vehicle.trim}
          </p>
          <p>
            <b>Country</b>: {vehicle.country}
          </p>
          <p>
            <b>Powertrain Type</b>: {vehicle.powertrain}
          </p>
          <p>
            <b>Restraint Type</b>: {vehicle.restraint}
          </p>
          <p>
            <b>Body Type</b>: {vehicle.body_type}
          </p>
          <p>
            <b>Info Source</b>: {vehicle.info_source}
          </p>
          <p>
            <b>Tags</b>: {vehicle.tags ? vehicle.tags.join(", ") : "none"}
          </p>
        </Grid>
        <Grid item md={12} className={classes.textCenterAlign}>
          {vehicle.log_level != null && (
            <p>
              <b>Log Level</b>: {vehicle.log_level}
            </p>
          )}
          {vehicle.canbus && (
            <>
              <p>
                <b>CANBus Enabled</b>: {vehicle.canbus.enabled.toString()}
              </p>
              <p>
                <b>Max Memory Buffer Size</b>: {vehicle.canbus.max_mem_buffer_size ?? "Default"}
              </p>
              <p>
                <b>Data Logger 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>
              <p>
                <b>DTC Enabled</b>: {(vehicle.canbus.dtc_enabled || false).toString()}
              </p>
            </>
          )}
          <p>
            <b>DLT Logging Enabled</b>: {(vehicle.dlt_enabled || false).toString()}
          </p>
          {vehicle.dlt_enabled && (
            <p>
              <b>DLT Level</b>: {findDLTLevelStr(vehicle.dlt_level) ?? "Default"}
            </p>
          )}
        </Grid>
        <Grid
          item
          md={12}
          className={classes.textCenterAlign}
        >
          <Box sx={{
            display: "flex",
            justifyContent: "center",
            alignItems: "flex-end"
          }}>
            <p>
              <b>IDPS Enabled</b>: {(vehicle.idps_enabled || false).toString()}
            </p>
          </Box>
        </Grid>
        {showDebugMask && (
          <Grid item md={12} className={classes.textCenterAlign}>
            <p>
              <b>Debug Mask</b>: {vehicle.debug_mask}
            </p>
          </Grid>
        )}
        <Grid
          item
          md={12}
          className={classes.textCenterAlign}
        >
          <Box sx={{
            display: "flex",
            justifyContent: "center",
            alignItems: "flex-end"
          }}>
            <RoleWrap
              groups={groups}
              providers={providers}
              rolesPerProvider={Permissions.FiskerUpdateDeploy}
            >
              <FormControlLabel
                label="Force Config Update"
                control={
                  <Checkbox
                    checked={forced}
                    onChange={onForcedChange}
                  />
                }
              />
              <Tooltip key={`push-config-${vin}`} title={`Push Config Update to "${vin}"`}>
                <Link to="#" onClick={() => setShowUploadConfigModal(true)}  >
                  <UploadIcon aria-label={`Push Config Update to "${vin}"`} fontSize="large" />
                </Link>
              </Tooltip>
            </RoleWrap>
          </Box>
        </Grid>
        <Grid item md={12} className={classes.textCenterAlign}>
          <RoleWrap
            groups={groups}
            providers={providers}
            rolesPerProvider={Permissions.FiskerMagnaCreate}
          >
            <Tooltip key={`update-${vin}`} title={`Update "${vin}"`}>
              <Link to={`/vehicle-update?vin=${vin}`} style={{ margin: 5 }}>
                <EditIcon aria-label={`Update "${vin}"`} fontSize="large" />
              </Link>
            </Tooltip>
          </RoleWrap>
        </Grid>
      </Grid>
      <GeneralConfirmation
        message={"push config update to:" + vin}
        open={showUploadConfigModal}
        close={() => setShowUploadConfigModal(false)}
        actionFunction={onUploadConfig}
        title="Send Update"
      />
    </div>
  );
};

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

export default CarDetails;
