/* eslint-disable react/jsx-key */
/* eslint-disable react/jsx-props-no-spreading */
import React, { useEffect, useState } from "react";
import { Button, Grid, Paper, Typography, TextField } from "@mui/material";
import { makeStyles } from "@mui/styles";

import { observer } from "mobx-react";
import { useNavigate } from "react-router-dom";

import BuildIcon from "@mui/icons-material/Build";
import { applySnapshot, fromSnapshot, getSnapshot } from "mobx-keystone";
import { ipcRenderer } from "electron";
import { getRootStore, RootStore } from "../../../models/root-store.ts";

const useStyles = makeStyles({
  content: {
    alignItems: "center",
  },
  root: {
    flexGrow: 1,
  },
  paper: {
    backgroundColor: "#95A5A6",
    textAlign: "center",
  },
  paperInput: {
    backgroundColor: "#666666",
    alignItems: "center",
    justifyContentItems: "baseline",
    padding: 10,
    margin: 10,
    minHeight: 70,
  },
  paperTelemetry: {
    backgroundColor: "#666666",
    alignItems: "center",
    justifyContentItems: "baseline",
    padding: 10,
    margin: 10,
    minHeight: 20,
  },
  paperInputNested: {
    backgroundColor: "#7d7d7d",
    alignItems: "center",
    justifyContentItems: "baseline",
    padding: 10,
    margin: 10,
    minHeight: 70,
  },
  paperUpdate: {
    backgroundColor: "#EAEAEA",
    alignItems: "center",
    justifyContentItems: "baseline",
    padding: 10,
    margin: 10,
    minHeight: 50,
  },
  buttons: {
    backgroundColor: "#666666",
    alignItems: "center",
    alignSelf: "center",
    padding: 10,
    margin: 10,
    minHeight: 70,
  },
  gridItemButton: {
    margin: 0,
    padding: 0,
    textAlign: "center",
  },
  button: {
    backgroundColor: "#3E3E3E",
    height: "90%",
    width: "90%",
    margin: 25,
    padding: 25,
    textAlign: "center",
  },
  typo: {
    fontSize: "auto",
  },
  paperTop: {
    alignItems: "center",
    padding: 10,
    marginTop: 15,
    margin: 15,
  },
  typoAddTicket: {
    marginLeft: 25,
    marginTop: 10,
    marginBottom: 10,
  },
  input: {
    color: "white",
    fontSize: "1.1em",
    padding: "5px",
    width: "auto",
  },
  inputLabel: {
    color: "black",
    fontSize: "20px",
  },
  inputNumbers: {
    color: "white",
    fontSize: "1.2em",
    padding: "5px",
    width: "auto",
  },
  buttonInput: {
    backgroundColor: "#666666",
    alignItems: "center",
    justifyContentContent: "center",
    padding: 20,
    marginTop: 20,
    marginLeft: 10,
  },
});

const ToolsRootStore = () => {
  const classes = useStyles();
  const history = useNavigate();
  const [rootStore] = useState(() => getRootStore());

  const ioLoopChanged = async (e: any) => {
    if (rootStore.settings.applicationMode === 1) {
      // Below is to listen to ws events for the push button
      if (e.id === rootStore.printerList.defaultPrinterButtonId) {
        rootStore.printerList.setDefaultPrinterButtonState(e.state);
      }
      // Below is to check if the loop is active
      if (e.id === rootStore.auxList.defaultLoopId) {
        rootStore.auxList.setDefaultLoopState(e.state);
        // Check if we have ticket on loop enabled
      }
    } else if (rootStore.settings.applicationMode === 5) {
      if (e.id === rootStore.auxList.defaultLoopId) {
        rootStore.auxList.setDefaultLoopState(e.state);
      }
    } else if (rootStore.settings.applicationMode === 2) {
      if (e.id === rootStore.auxList.defaultLoopId) {
        rootStore.auxList.setDefaultLoopState(e.state);
      }
    }
  };

  const printerChanged = async (e: any) => {
    if (rootStore.settings.applicationMode === 1) {
      if (e.printer === rootStore.printerList.defaultPrinterId) {
        rootStore.printerList.setPrinterState(e.status);
      }
    }
  };

  const passageChanged = async (e: any) => {
    if (
      rootStore.settings.applicationMode === 5 ||
      rootStore.settings.applicationMode === 1 ||
      rootStore.settings.applicationMode === 2
    ) {
      if (e.id === rootStore.passageList.defaultPassageId) {
        rootStore.passageList.setActionState(e.action);
      }
    }
  };

  const ioOutputAction = async (e: any) => {
    if (rootStore.settings.applicationMode === 5) {
      if (e.id === rootStore.auxList.defaultLostTicketOutputId) {
        rootStore.auxList.setAuxLostTicketActionState(e.action);
      } else if (e.id === rootStore.auxList.defaultUnknownTicketOutputId) {
        rootStore.auxList.setDefaultUnknownTicketOutputState(e.action);
      }
    }
  };

  useEffect(() => {
    ipcRenderer.on(
      "workerWindowNetwork->mainWindow-ws-ioLoopChanged",
      (event, args) => {
        console.log("RECEIVED IPC FROM LOOP workerNetwork");
        ioLoopChanged(args);
      }
    );
    ipcRenderer.on(
      "workerWindowNetwork->mainWindow-ws-printerChanged",
      (event, args) => {
        printerChanged(args);
      }
    );
    ipcRenderer.on(
      "workerWindowNetwork->mainWindow-ws-passageChanged",
      (event, args) => {
        passageChanged(args);
      }
    );
    ipcRenderer.on(
      "workerWindowNetwork->mainWindow-ws-ioOutputAction",
      (event, args) => {
        ioOutputAction(args);
      }
    );
    return () => {
      ipcRenderer.removeAllListeners(
        "workerWindowNetwork->mainWindow-ws-ioLoopChanged"
      );
      ipcRenderer.removeAllListeners(
        "workerWindowNetwork->mainWindow-ws-printerChanged"
      );
      ipcRenderer.removeAllListeners(
        "workerWindowNetwork->mainWindow-ws-passageChanged"
      );
      ipcRenderer.removeAllListeners(
        "workerWindowNetwork->mainWindow-ws-ioOutputAction"
      );
    };
  }, []);

  const stateToHumanReadable = (state: number) => {
    switch (state) {
      case 0:
        return "rest state";
      case 1:
        return "opened";
      case 2:
        return "stoped";
      case 3:
        return "closed";
      case 4:
        return "continously open";
      case 5:
        return "deactivate continously open";
      default:
        return "rest state";
    }
  };

  return (
    <Grid container justifyContent="center" spacing={0}>
      <Grid item xs={12} md={12} lg={10} xl={8}>
        <Paper className={classes.paperTelemetry}>
          <Grid container justifyContent="center" spacing={0}>
            {rootStore.passageList.defaultPassage ? (
              <>
                <Typography variant="h6" noWrap style={{ paddingRight: 20 }}>
                  {`Passage action ( ${rootStore.passageList.defaultPassage?.name.toString()} ):`}
                </Typography>
                <Typography
                  variant="h6"
                  noWrap
                  style={{ color: "white", paddingRight: 20 }}
                >
                  {stateToHumanReadable(rootStore.passageList.actionState)}
                </Typography>
              </>
            ) : (
              <Typography variant="h6" noWrap style={{ paddingRight: 20 }}>
                Passage not configured
              </Typography>
            )}

            {rootStore.auxList.defaultLoopConfigured ? (
              <>
                <Typography variant="h6" noWrap style={{ paddingRight: 20 }}>
                  {`Loop (${rootStore.auxList.defaultLoop?.name.toString()} ):`}
                </Typography>
                <Typography
                  variant="h6"
                  noWrap
                  style={{ color: "white", paddingRight: 20 }}
                >
                  {rootStore.auxList.defaultLoopState?.toString()}
                </Typography>
              </>
            ) : (
              <Typography variant="h6" noWrap style={{ paddingRight: 20 }}>
                Loop not configured
              </Typography>
            )}

            {rootStore.printerList.defaultPrinterButton ? (
              <>
                <Typography variant="h6" noWrap style={{ paddingRight: 20 }}>
                  {`Printer button: (${rootStore.printerList.defaultPrinterButton.name.toString()} ):`}
                </Typography>
                <Typography
                  variant="h6"
                  noWrap
                  style={{ color: "white", paddingRight: 20 }}
                >
                  {rootStore.printerList.defaultPrinterButtonState?.toString()}
                </Typography>
              </>
            ) : (
              <Typography variant="h6" noWrap style={{ paddingRight: 20 }}>
                Printer not configured
              </Typography>
            )}

            {rootStore.printerList.defaultPrinterButton ? (
              <>
                <Typography variant="h6" noWrap style={{ paddingRight: 20 }}>
                  {`Printer status : (${rootStore.printerList.defaultPrinter?.name.toString()} ):`}
                </Typography>
                <Typography
                  variant="h6"
                  noWrap
                  style={{ color: "white", paddingRight: 20 }}
                >
                  {rootStore.printerList.printerState?.toString()}
                </Typography>
              </>
            ) : null}
          </Grid>
        </Paper>
        <Paper className={classes.paperInput}>
          <Button
            variant="contained"
            color="primary"
            onClick={() => {
              ipcRenderer.postMessage(
                "mainWindow->main->workerWindowNetwork-openPassage",
                rootStore.passageList.defaultPassageId,
                []
              );
            }}
            style={{ padding: 25, marginBottom: 20 }}
            fullWidth
          >
            Open passage
          </Button>
          <Button
            variant="contained"
            color="primary"
            onClick={() => {
              ipcRenderer.postMessage(
                "mainWindow->main->workerWindowNetwork-controlPassage",
                [rootStore.passageList.defaultPassageId, 4],
                []
              );
            }}
            style={{ padding: 25, marginBottom: 20 }}
            fullWidth
          >
            Continously open passage
          </Button>
          <Button
            variant="contained"
            color="primary"
            onClick={() => {
              ipcRenderer.postMessage(
                "mainWindow->main->workerWindowNetwork-controlPassage",
                [rootStore.passageList.defaultPassageId, 5],
                []
              );
            }}
            style={{ padding: 25 }}
            fullWidth
          >
            Deactivate continously open passage
          </Button>
        </Paper>
        <Paper className={classes.paperInput}>
          <Button
            variant="contained"
            color="primary"
            onClick={() => {
              ipcRenderer.postMessage(
                "mainWindow->main-arm/disArm-scanner",
                [rootStore.settings.serialPortPath, true],
                []
              );
            }}
            style={{ padding: 25, marginBottom: 20 }}
            fullWidth
          >
            Activate scanner
          </Button>
          <Button
            variant="contained"
            color="primary"
            onClick={() => {
              ipcRenderer.postMessage(
                "mainWindow->main-arm/disArm-scanner",
                [rootStore.settings.serialPortPath, false],
                []
              );
            }}
            style={{ padding: 25 }}
            fullWidth
          >
            Deactivate scanner
          </Button>
        </Paper>
      </Grid>
    </Grid>
  );
};

export default observer(ToolsRootStore);
