/* eslint-disable react/jsx-key */
/* eslint-disable compat/compat */
/* eslint-disable radix */
import React, { useEffect, useState } from 'react';
import Grid from '@mui/material/Grid';
import { observer } from 'mobx-react';
import { ipcRenderer } from 'electron';
import { getRootStore } from '../../models/root-store.ts';
import HomeContentTopPayOnFoot from '../elements/HomeContentTopPayOnFoot';
import HomeContentTopVirtualPrinter from '../elements/HomeContentTopVirtualPrinter';
import HomeContentBottomVirtualPrinter from '../elements/HomeContentBottomVirtualPrinter';
import HomeContentBottomPayOnFoot from '../elements/HomeContentBottomPayOnFoot';
import HomeContentTopEntry from '../elements/HomeContentTopEntry';
import HomeContentBottomEntry from '../elements/HomeContentBottomEntry';
import HomeContentTopCounter from '../elements/HomeContentTopCounter';
import HomeContentBottomCounter from '../elements/HomeContentBottomCounter';
import ScreenSaver from '../elements/ScreenSaver';
import HomeContentTopExitPayInLane from '../elements/HomeContentTopExitPayInLane';
import HomeContentBottomExitPayInLane from '../elements/HomeContentBottomExitPayInLane';
import HomeContentTopExit from '../elements/HomeContentTopExit';
import HomeContentBottomExit from '../elements/HomeContentBottomExit';
import HomeContentBottomExitPayInLaneDatacap from '../elements/HomeContentBottomExitPayInLaneDatacap';

function Home() {
  const [rootStore] = useState(() => getRootStore());

  const printTicketProcess = async () => {
    if (typeof rootStore.acs01List.defaultAcs01 === 'undefined') return;
    // Authenticate on the Acs01
    if (
      rootStore.settings.applicationMode === 1 &&
      rootStore.terminal.ticketOnLoop
    ) {
      ipcRenderer.postMessage(
        'mainWindow->main->workerWindowNetwork-printTicket',
        [
          rootStore.scenarioList.defaultScenarioConfigured,
          rootStore.scenarioList.defaultScenarioId,
          rootStore.printerList.defaultPrinterId,
        ],
        []
      );
    }
  };

  const checkScenarioProcess = async () => {
    if (typeof rootStore.acs01List.defaultAcs01 === 'undefined') return;
    // Authenticate on the Acs01
    if (rootStore.scenarioList.defaultScenarioConfigured) {
      ipcRenderer.sendTo(
        rootStore.settings.workerWindowId,
        'mainWindow->workerWindowNetwork-checkScenario',
        [
          rootStore.scenarioList.defaultScenarioConfigured,
          rootStore.scenarioList.defaultScenarioId,
        ]
      );
    }
  };

  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) {
        if (rootStore.settings.screenSaverState) {
          if (typeof rootStore.acs01List.defaultAcs01 === 'undefined') return;
          rootStore.printerList.setNewPrintSequence(true);
          // Authenticate on the Acs01
          if (rootStore.settings.applicationMode === 1) {
            rootStore.printerList.setNewPrintCommandSend(true);
            await printTicketProcess();
          }
        }
      }
      // Below is to check if the loop is active
      let timer;
      if (e.id === rootStore.auxList.defaultLoopId) {
        rootStore.settings.setScreenSaverState(e.state);
        rootStore.auxList.setDefaultLoopState(e.state);
        // Check if we have ticket on loop enabled

        if (e.state === true) {
          timer = setTimeout(() => {
            rootStore.printerList.setNewPrintSequence(false);
            rootStore.printerList.setNewPrintCommandSend(false);
            rootStore.printerList.setPrinterState(0);
          }, 10000);
          if (!rootStore.terminal.ticketOnLoop) {
            rootStore.printerList.setNewPrintSequence(false);
            rootStore.printerList.setNewPrintCommandSend(false);
            return;
          }
          rootStore.printerList.setNewPrintSequence(true);
          rootStore.printerList.setNewPrintCommandSend(true);
          await printTicketProcess();
        } else if (e.state === false) {
          clearTimeout(timer);
          rootStore.printerList.setNewPrintSequence(false);
          rootStore.printerList.setNewPrintCommandSend(false);
        }
      }
    } else if (rootStore.settings.applicationMode === 5) {
      if (rootStore.auxList.defaultLoopConfigured === false) {
        return;
      }
      if (e.id === rootStore.auxList.defaultLoopId) {
        rootStore.auxList.setDefaultLoopState(e.state);
        if (rootStore.terminal.scannerConnectedToDisplay) {
          if (e.state === false) {
            rootStore.ui.setEmvPaymentNotNeccessary(false);
            rootStore.ui.setPriceToPay(-1);
            rootStore.ui.setCreditsError(false);
          }
          ipcRenderer.postMessage(
            'mainWindow->main-arm/disArm-scanner',
            [rootStore.settings.serialPortPath, e.state],
            []
          );
        }
        rootStore.settings.setScreenSaverState(e.state);
        if (rootStore.scenarioList.defaultScenarioConfigured)
          await checkScenarioProcess();
      }
    } else if (rootStore.settings.applicationMode === 2) {
      if (rootStore.auxList.defaultLoopConfigured === false) {
        return;
      }
      if (e.id === rootStore.auxList.defaultLoopId) {
        rootStore.auxList.setDefaultLoopState(e.state);
        if (rootStore.terminal.scannerConnectedToDisplay) {
          ipcRenderer.postMessage(
            'mainWindow->main-arm/disArm-scanner',
            [rootStore.settings.serialPortPath, e.state],
            []
          );
        }
        rootStore.settings.setScreenSaverState(e.state);
      }
    }
  };

  const printerChanged = async (e: any) => {
    if (rootStore.settings.applicationMode === 1) {
      if (e.printer === rootStore.printerList.defaultPrinterId) {
        rootStore.printerList.setPrinterState(e.status);
        // Logic for giving ticket on the loop
        rootStore.printerList.setNewPrintCommandSend(false); // not sure
        if (rootStore.printerList.newPrintSequence && e.status === 4) {
          rootStore.printerList.setNewPrintSequence(false);
        }
      }
    }
  };

  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);
      }
    }
  };

  ipcRenderer.on('workerWindowNetwork->main-loopInitStateResponse', (_event, data) => {
    if (data && data?.id && typeof data.state !== 'undefined') {
      console.log('📥 Initial loop state received from worker:', data);
  
      ioLoopChanged({
        id: data.id,
        state: data.state,
      });
    } else {
      console.warn('⚠️ Invalid initial loop state received:', data);
    }
  });
  

  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'
      );
      ipcRenderer.removeAllListeners('workerWindowNetwork->main-loopInitStateResponse');
    };
  }, []);

  return (
    <>
      {rootStore.settings.screenSaverEnabled &&
      !rootStore.settings.screenSaverState ? (
        <Grid
          container
          spacing={0}
          direction="column"
          alignItems="center"
          justifyContent="center"
          style={{
            overflow: 'hidden',
            minHeight: '85vh',
          }}
        >
          <ScreenSaver />
        </Grid>
      ) : null}
      {rootStore.settings.applicationMode === 0 ? (
        <HomeContentTopVirtualPrinter />
      ) : null}

      {rootStore.settings.screenSaverEnabled &&
      rootStore.settings.screenSaverState &&
      rootStore.settings.applicationMode === 1 ? (
        <Grid
          container
          spacing={0}
          direction="column"
          alignItems="center"
          justifyContent="center"
          style={{
            overflow: 'hidden',
            minHeight: '85vh',
          }}
        >
          <HomeContentTopEntry />
          <HomeContentBottomEntry />
        </Grid>
      ) : null}

      {rootStore.settings.screenSaverEnabled &&
      rootStore.settings.screenSaverState &&
      rootStore.settings.applicationMode === 5 ? (
        <Grid
          container
          spacing={0}
          direction="column"
          alignItems="center"
          justifyContent="center"
          style={{
            overflow: 'hidden',
            minHeight: '85vh',
          }}
        >
          <HomeContentTopExitPayInLane />
          {rootStore.settings.emvDatacap ? (
            <HomeContentBottomExitPayInLaneDatacap />
          ) : (
            <HomeContentBottomExitPayInLane />
          )}
        </Grid>
      ) : null}

      {rootStore.settings.screenSaverEnabled &&
      rootStore.settings.screenSaverState &&
      rootStore.settings.applicationMode === 2 ? (
        <Grid
          container
          spacing={0}
          direction="column"
          alignItems="center"
          justifyContent="center"
          style={{
            overflow: 'hidden',
            minHeight: '85vh',
          }}
        >
          <HomeContentTopExit />
          <HomeContentBottomExit />
        </Grid>
      ) : null}

      {rootStore.settings.screenSaverEnabled &&
      rootStore.settings.screenSaverState &&
      rootStore.settings.applicationMode === 3 ? (
        <Grid
          container
          spacing={0}
          direction="column"
          alignItems="center"
          justifyContent="center"
          style={{
            overflow: 'hidden',
            minHeight: '85vh',
          }}
        >
          <HomeContentTopPayOnFoot />
          <HomeContentBottomPayOnFoot />
        </Grid>
      ) : null}

      {rootStore.settings.applicationMode === 6 ? (
        <Grid
          container
          spacing={0}
          direction="column"
          alignItems="center"
          justifyContent="center"
          style={{
            overflow: 'hidden',
            minHeight: '85vh',
          }}
        >
          <HomeContentTopCounter />
          <HomeContentBottomCounter />
        </Grid>
      ) : null}

      {rootStore.settings.applicationMode === 7 ? (
        <Grid
          container
          spacing={0}
          direction="column"
          alignItems="center"
          justifyContent="center"
          style={{
            overflow: 'hidden',
            minHeight: '85vh',
          }}
        >
          <HomeContentTopCounter />
          <HomeContentBottomCounter />
        </Grid>
      ) : null}

      {rootStore.settings.applicationMode === 0 ? (
        <HomeContentBottomVirtualPrinter />
      ) : null}
    </>
  );
}

export default observer(Home);
