import React, { useEffect, useState } from "react";
import { Redirect } from "react-router";
import { Link } from 'react-router-dom';
import {
  Grid,
  Table,
  TableBody,
  TableCell,
  TableFooter,
  TableRow,
  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";
import TableHeaderSortable from "../../../Table/HeaderSortable";

const tableColumns = [
  {
    id: "flashpack",
    label: "Flashpack",
  },
  {
    id: "vehicles",
    label: "# of Vehicles in Fleet",
  },
];

const MainForm = ({ name }) => {
  const classes = useStyles();
  const { setMessage } = useStatusContext();
  const { fleet, getFleet, deleteFleet, fleetFlashpackInfo, getFleetFlashpackInfo } = 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);
        await getFleetFlashpackInfo(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_count || 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>
        )}
        <Grid item md={12} className={classes.textCenterAlign}>
          <p>
            <b>IDPS Enabled</b>: {(fleet.idps_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 ids={fleet.vehicles} actions={["addTags", "updateConfig", "sms"]} />
        </Grid>
      </Grid>
      <Grid item md={12} className={classes.textCenterAlign}>
        <div className={clsx(classes.paper, classes.tableSize)}>
          <Grid container className={classes.root} spacing={2}>
            <Grid item md={12} className={classes.textCenterAlign}>
              <p>
                <b>Flashpack Information</b>
              </p>
            </Grid>
          </Grid>
          {fleetFlashpackInfo && (<Table size="small" >
            <TableHeaderSortable
              classes={classes}
              orderBy={"flashpack"}
              order={"asc"}
              columnData={tableColumns}
              onSortRequest={() => { return null }}
            />
            <TableBody>
              {
                fleetFlashpackInfo.data && Object.entries(fleetFlashpackInfo.data).map(([flashpack, occurrences]) => (
                  <TableRow key={`${flashpack}-${occurrences.toString()}`}>
                    <TableCell align="center">{flashpack}</TableCell>
                    <TableCell align="center">{occurrences.toString()}</TableCell>
                  </TableRow>
                ))
              }
            </TableBody>
            <TableFooter>
              <TableRow>
                {!fleetFlashpackInfo || fleetFlashpackInfo.length === 0 ? (
                  <TableCell colSpan={2} align="center">No flashpack info for fleet</TableCell>
                ) : <></>}
              </TableRow>
            </TableFooter>
          </Table>)}
        </div>
      </Grid>
      <DeleteConfirmation message={name} open={showDeleteModal} close={() => setShowDeleteModal(false)} deleteFunction={onDelete} />
    </div >
  );
};

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

export default FleetDetails;
