import { Checkbox, FormControlLabel, Grid, Tooltip } from "@material-ui/core";
import DeleteIcon from "@material-ui/icons/Delete";
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 { 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 GeneralConfirmation from "../../../GeneralConfirmation";
import useStyles from "../../../useStyles";

const MainForm = ({ vin }) => {
  const classes = useStyles();
  const { setMessage } = useStatusContext();
  const { vehicle, getVehicle, deleteVehicle, uploadConfig } = useVehicleContext();
  const [redirect, setRedirect] = useState(null);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  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 onDelete = async () => {
    try {
      await deleteVehicle(vin, token);
      setMessage(`Deleted ${vin}`);
      setRedirect(`/vehicles`);
    } catch (e) {
      setMessage(e.message);
      logger.warn(e.stack);
    }
  };

  const onUploadConfig = async () => {
    try {
      await uploadConfig(vin, forced, token);
      setMessage(`Config Uploaded ${vin}`);
    } 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>
          <p>
            <b>ICCID</b>: {vehicle.iccid}
          </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>
          </>
        )}
          </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}>
          <RoleWrap
              groups={groups}
              providers={providers}
              rolesPerProvider={Permissions.FiskerCreate}
            >
            <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>
        </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>
          <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}"`} fontSize="large" />
              </Link>
            </Tooltip>
          </RoleWrap>
        </Grid>
      </Grid>
      <DeleteConfirmation
        message={vin}
        open={showDeleteModal}
        close={() => setShowDeleteModal(false)}
        deleteFunction={onDelete}
      />
      <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;
