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

import { useUserContext } from "../../../Contexts/UserContext"
import { useStatusContext } from "../../../Contexts/StatusContext";
import { FleetProvider, useFleetContext } from "../../../Contexts/FleetContext"
import useStyles from "../../../useStyles";
import { logger } from "../../../../services/monitoring";
import DeleteConfirmation from "../../../DeleteConfirmation";
import BulkActions from "../../../BulkActions";

const MainForm = ({ name }) => {
  const classes = useStyles();
  const { setMessage } = useStatusContext();
  const { fleet, getFleet, deleteFleet } = useFleetContext();
  const [redirect, setRedirect] = useState(null);
  const [showDeleteModal, setShowDeleteModal] = useState(false)
  const { token: { idToken: { jwtToken: token } } } = useUserContext();

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

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

  const onDelete = async () => {
    try {
      await deleteFleet(name, token);
      setMessage(`Deleted ${name}`)
      setRedirect(`/fleets`);
    } 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>Name</b>: {name}</p>
          <p><b>Vehicles</b>: {fleet.vehicles ? fleet.vehicles.length : 0}</p>
          {fleet.log_level != null && (
            <p><b>Log Level</b>: {fleet.log_level}</p>
          )}
        </Grid>
        {fleet.canbus && (
          <Grid item md={12} className={classes.textCenterAlign}>
            <b>CANBus</b>
            <p><b>Enabled</b>: {fleet.canbus.enabled.toString()}</p>
            <p><b>Max Memory Buffer Size</b>: {fleet.canbus.max_mem_buffer_size ?? "Default"}</p>
            <p><b>Enabled</b>: {fleet.canbus.data_logger_enabled.toString()}</p>
            <p><b>Max Disk Buffer Size</b>: {fleet.canbus.max_disk_buffer_size ?? "Default"}</p>
            <p><b>Filters</b>: {fleet.canbus.filters ? fleet.canbus.filters.length : 0}</p>
            <p><b>DTC Enabled</b>: {(fleet.canbus.dtc_enabled || false).toString()}</p>
          </Grid>
        )}
        {showDebugMask && (
          <Grid item md={12} className={classes.textCenterAlign}>
            <p>
              <b>Debug Mask</b>: {fleet.debug_mask}
            </p>
          </Grid>
        )}
        <Grid item md={12} className={classes.textCenterAlign}>
          <Tooltip key={`update-${name}`} title={`Update "${name}"`}>
            <Link to={`/fleet-update?name=${name}`} style={{ margin: 5 }}>
              <EditIcon aria-label={`Update "${name}"`} />
            </Link>
          </Tooltip>
          <Tooltip key={`delete-${name}`} title={`Delete "${name}"`}>
            <Link to="#" onClick={() => setShowDeleteModal(true)}>
              <DeleteIcon aria-label={`Delete "${name}"`} />
            </Link>
          </Tooltip>
        </Grid>
        <Grid item md={12} className={classes.textCenterAlign}>
          <BulkActions vins={fleet.vehicles} />
        </Grid>
      </Grid>
      <DeleteConfirmation message={name} open={showDeleteModal} close={() => setShowDeleteModal(false)} deleteFunction={onDelete} />
    </div >
  );
};

const FleetDetails = (props) => (
  <FleetProvider>
    <MainForm {...props} />
  </FleetProvider>
);

export default FleetDetails;
