/* eslint-disable react/jsx-key */
/* eslint-disable compat/compat */
/* eslint-disable radix */
import React, { useEffect, useState } from 'react';
import { Grid, Paper, Typography, Fab } from '@mui/material';
import { makeStyles } from '@mui/styles';
import {
  compareAsc,
  differenceInSeconds,
  format,
  formatDistanceStrict,
  formatDuration,
  fromUnixTime,
  intervalToDuration,
} from 'date-fns';
import { observer } from 'mobx-react';
import { useNavigate } from 'react-router-dom';
import { ipcRenderer } from 'electron';
import TimelineOppositeContent from '@mui/lab/TimelineOppositeContent';
import TimelineDot from '@mui/lab/TimelineDot';
import TimeToLeave from '@mui/icons-material/TimeToLeave';
import TimelineItem from '@mui/lab/TimelineItem';
import TimelineSeparator from '@mui/lab/TimelineSeparator';
import TimelineConnector from '@mui/lab/TimelineConnector';
import TimelineContent from '@mui/lab/TimelineContent';
import Timeline from '@mui/lab/Timeline';
import Timelapse from '@mui/icons-material/Timelapse';
import Schedule from '@mui/icons-material/Schedule';
import CheckBoxOutlineBlankIcon from '@mui/icons-material/CheckBoxOutlineBlank';
import CheckBoxIcon from '@mui/icons-material/CheckBox';
import fetch from 'electron-fetch';
import ScannedTicket from '../../models/Application/ScannedTicket';
import { getRootStore } from '../../models/root-store';
import Tarif from '../../models/Application/Tarif';
import Template from '../../models/Application/Template';
import Log from '../../models/Logs/Log';
import ScannedTicketSimple from '../../models/Application/ScannedTicketSimple';

function getRandomInt(min: number, max: number) {
  const mini = Math.ceil(min);
  const maxi = Math.floor(max);
  return Math.floor(Math.random() * (maxi - mini) + mini); // The maximum is exclusive and the minimum is inclusive
}

const useStyles = makeStyles({
  content: {
    alignItems: 'center',
    '@media print': {
      display: 'none',
    },
  },
  typoAddTicket: {
    marginLeft: 5,
    marginTop: 10,
    marginBottom: 10,
  },
  buttonTicketLost: {
    marginTop: 10,
    paddingTop: 70,
    paddingBottom: 70,
    paddingLeft: 90,
    paddingRight: 90,
    margins: 20,
  },
  paper: {
    alignItems: 'center',
    padding: 10,
    marginTop: -10,
    margin: 20,
    '@media print': {
      display: 'none',
    },
  },
  paperTop: {
    alignItems: 'center',
    padding: 15,
    marginTop: 100,
    margin: 20,
    '@media print': {
      display: 'none',
    },
  },
  paperTopPay: {
    alignItems: 'center',
    padding: 15,
    marginTop: 10,
    margin: 20,
    '@media print': {
      display: 'none',
    },
  },
  paperTopPayContent: {
    alignItems: 'center',
    padding: 15,
    marginTop: 0,
    margin: 20,
    '@media print': {
      display: 'none',
    },
  },
});

function HomeContentBottomExitPayInLaneDatacap() {
  const [rootStore] = useState(() => getRootStore());
  // const [emvCommandSend, setEmvCommandSend] = useState(false);

  const classes = useStyles();
  const [state, setState] = React.useState('nothing');
  const [scannedTicket, setScannedTicket] = React.useState<ScannedTicket>();
  const [unlimitedCredits, setUnlimitedCredits] = React.useState(false);
  const [template, setTemplate] = React.useState<Template>();
  const [tarif, setTarif] = React.useState<Tarif>();
  const [startTime, setStartTime] = useState<Date>();
  const [endTime, setEndTime] = useState<Date>();
  const [time, setTime] = useState(format(new Date(), 'HH:mm:ss - dd/MM/yyyy'));
  const [timeMomentPay, setTimeMomentPay] = useState(new Date());

  const checkTime = () => {
    let localState = 0;
    if (endTime) {
      localState = compareAsc(timeMomentPay, endTime);
      setState(localState.toString());
      return true;
    }
    return false;
  };

  const checkDistanceWords = () => {
    let localDistance = '';
    if (endTime) {
      localDistance = formatDistanceStrict(timeMomentPay, endTime);
    }
    return localDistance;
  };

  const checkDistanceHoursMinutes = () => {
    let localDistance;

    if (endTime) {
      localDistance = intervalToDuration({
        start: timeMomentPay,
        end: endTime,
      });

      const formated = formatDuration(localDistance, {
        delimiter: ', ',
      });
      return formated;
    }
    return '';
  };

  async function fetchEmv(urlEmv: string, amount: string) {
    console.log('fetchEmv called with:', urlEmv, amount);
    const result = await ipcRenderer.invoke('datacap-sendAmount', {
      merchantId: rootStore.settings.merchantId,
      operatorId: rootStore.settings.operatorId,
      tranDeviceId: rootStore.settings.tranDeviceId,
      ipEmv: urlEmv,
      amount,
    });
    console.log('fetchEmv response:', result);
    return result;
  }

  // --- EMV logging helpers (ADD THESE) ---
function buildEmvLogReason(r: any = {}, extra: { ticketId?: any; amountStr?: string } = {}) {
  const { ticketId = '', amountStr = '' } = extra;
  return [
    `TicketId: ${String(ticketId)}`,
    `Amount: ${amountStr}`,
    `CmdStatus: ${r.CmdStatus ?? ''}`,
    `DSIXReturnCode: ${r.DSIXReturnCode ?? ''}`,
    `TextResponse: ${r.TextResponse ?? ''}`,
    `AuthCode: ${r.AuthCode ?? ''}`,
    `InvoiceNo: ${r.InvoiceNo ?? ''}`,
    `Purchase: ${r.Purchase ?? amountStr}`,
    `Authorize: ${r.Authorize ?? amountStr}`,
    `CardType: ${r.CardType ?? ''}`,
    `EntryMethod: ${r.EntryMethod ?? ''}`,
    `RefNo: ${r.RefNo ?? ''}`,
  ].join(' | ');
}

function logEmvOutcome(
  outcome:
    | 'Payment successful'
    | 'Declined'
    | 'Cancelled'
    | 'Timeout'
    | 'Error'
    | 'No response'
    | 'Exception',
  r: any,
  extra: { ticketId?: any; amountStr?: string } = {}
) {
  rootStore.logs.addLog(
    new Log({
      type: 'Application',
      subType: 'EMV',
      name: `EMV: ${outcome}`,
      reason: buildEmvLogReason(r, extra),
      user: 'System',
    })
  );
}

  const emvSendAmount = async (
    amount: number,
    ticketId: any,
    unlimCreds: any
  ) => {
    try {
      const sendEmvAmountToDevice = await fetchEmv(
        rootStore.settings.ipEMV,
        amount.toFixed(2).toString()
      );
      const r = sendEmvAmountToDevice?.RStream ?? {};
      const amountStr = amount.toFixed(2);

      console.log('*-*-*- data', sendEmvAmountToDevice);
  
      const { RStream } = sendEmvAmountToDevice || {};
      if (!sendEmvAmountToDevice || !RStream) {
        logEmvOutcome('No response', {}, { ticketId, amountStr });
        rootStore.ui.setPriceToPay(-1);
        await ipcRenderer.invoke('datacap-resetEmv', {
          merchantId: rootStore.settings.merchantId,
          operatorId: rootStore.settings.operatorId,
          tranDeviceId: rootStore.settings.tranDeviceId,
          ipEmv: rootStore.settings.ipEMV,
        });
        return;
      }
      const status = RStream?.CmdStatus || '';
      const text = RStream?.TextResponse || '';
  
      const isRefused =
      status === 'Declined' ||
      (status === 'Error' &&
        (/DECLINED|NOT\s*APPROVED|DO\s*NOT\s*HONOR|REFUSED/i.test(text) ||
         /GENERAL\s+FAILURE/i.test(text))) ||
      /DECLINED|NOT\s*APPROVED|DO\s*NOT\s*HONOR|REFUSED/i.test(text);
    
  
      if (isRefused) {
        console.log('*-*-*- EMV Refused/Declined:', text || status);
        logEmvOutcome('Declined', r, { ticketId, amountStr });

        rootStore.ui.setPriceToPay(-1);
        rootStore.ui.setEmvTransactionCancelled(true);
  
        setTimeout(async () => {
          await ipcRenderer.invoke('datacap-resetEmv', {
            merchantId: rootStore.settings.merchantId,
            operatorId: rootStore.settings.operatorId,
            tranDeviceId: rootStore.settings.tranDeviceId,
            ipEmv: rootStore.settings.ipEMV,
          });
          rootStore.ui.setEmvTransactionCancelled(false);
        }, 3000);
  
        return; 
      }

      if (RStream?.CmdStatus === 'Error') {
        const reason = RStream?.TextResponse || 'Unknown error';
        console.log('*-*-*- EMV Error:', reason);
  
        const knownIssues = [
          'TRANSACTION CANCELLED - Operation Cancelled.',
          'TRANSACTION NOT COMPLETE - Timeout Waiting for PinPad.',
        ];
        const isCancelled =
        reason.startsWith('TRANSACTION CANCELLED') || /CANCELLED/i.test(reason);
      const isTimeout =
        reason.startsWith('TRANSACTION NOT COMPLETE - Timeout') || /TIMEOUT/i.test(reason);
    
      if (isCancelled) {
        logEmvOutcome('Cancelled', r, { ticketId, amountStr });
      } else if (isTimeout) {
        logEmvOutcome('Timeout', r, { ticketId, amountStr });
      } else {
        logEmvOutcome('Error', r, { ticketId, amountStr });
      }
  
        if (
          knownIssues.includes(reason) ||
          reason.startsWith('TRANSACTION NOT COMPLETE')
        ) {
          console.log('*-*-*- Resetting EMV due to known failure');
  
          rootStore.ui.setPriceToPay(-1);
          rootStore.ui.setEmvTransactionCancelled(true);
  
          setTimeout(async () => {
            await ipcRenderer.invoke('datacap-resetEmv', {
              merchantId: rootStore.settings.merchantId,
              operatorId: rootStore.settings.operatorId,
              tranDeviceId: rootStore.settings.tranDeviceId,
              ipEmv: rootStore.settings.ipEMV,
            });
            rootStore.ui.setEmvTransactionCancelled(false);
          }, 3000);
  
          return; // prevent fall-through to success path
        }
        // If it's some other "Error" that isn't known, just continue to the rest
        // (you can early-return here too if you want the same cancelled screen)
      }
  
      // Success path
      if (RStream?.Authorize === amountStr && RStream?.Purchase === amountStr) {
        // Valid transaction
        if (unlimCreds === false) {
          const scannedTicketCredits = scannedTicket?.credits || 1;
          scannedTicket?.setCredits(
            scannedTicketCredits - rootStore.scannedTicketList.weightToSubstractCredits
          );
        }
  
        if (rootStore.ui.wantsProofOfPayment) {
          const constructedArr = {
            title: rootStore.ui.title,
            itemText: rootStore.ui.itemText,
            dateTime: new Date().toLocaleString(),
            btw: rootStore.ui.btw,
            amount: amount.toFixed(2).toString(),
            method: RStream?.CardType,
            goodBy: rootStore.ui.goodBy,
            lang: 'US',
          };
          ipcRenderer.postMessage('mainSendToPrint', constructedArr, []);
        }
  
     

        logEmvOutcome('Payment successful', r, { ticketId, amountStr });
        rootStore.ui.setEmvPaymentSuccess(true);
        rootStore.ui.setViewCancel(false);
        ipcRenderer.postMessage(
          'mainWindow->main->workerWindowNetwork-openPassage',
          rootStore.passageList.defaultPassageId,
          []
        );
        rootStore.ui.setPriceToPay(-1);
        await ipcRenderer.invoke('datacap-resetEmv', {
          merchantId: rootStore.settings.merchantId,
          operatorId: rootStore.settings.operatorId,
          tranDeviceId: rootStore.settings.tranDeviceId,
          ipEmv: rootStore.settings.ipEMV,
        });
      }
  
    } catch (error) {
      logEmvOutcome('Exception', { TextResponse: String(error) }, { ticketId, amountStr: amount.toFixed(2) });
      console.error('error while fetching from EMV');
      return '';
    }
  };
  



  const checkPay = async (endDateTicket: any, tarifScannedTicket: any) => {
    if (typeof endDateTicket === 'undefined') return -1;
    if (typeof tarifScannedTicket === 'undefined') return -1;
    const endDateScannedTicket = new Date(endDateTicket);
    // The endTime is on location 1 of the array [1]
    let localDistanceSeconds = 0;
    localDistanceSeconds = differenceInSeconds(
      new Date(),
      endDateScannedTicket
    );
    setTime(format(new Date(), 'HH:mm:ss - dd/MM/yyyy'));
    setTimeMomentPay(new Date());
    let localPriceToPay;
    if (tarifScannedTicket) {
      localPriceToPay = await tarifScannedTicket.priceToPay(
        localDistanceSeconds
      );
    }
    if (
      typeof localPriceToPay === 'number' &&
      localPriceToPay !== -1 &&
      localPriceToPay >= 0
    ) {
      return localPriceToPay;
    }
    return -1;
  };

  // Regular expression to check if string is a valid UUID
  const regexExp =
    /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi;

  const handleDecode = async (result: any, onlineTicketResponse: any) => {
    // Checks

    if (result === null && typeof onlineTicketResponse === 'undefined') {
      console.log('1');
      return 0;
    }
    if (
      typeof onlineTicketResponse === 'undefined' &&
      (regexExp.test(rootStore.settings.serialMessage) === true ||
        /^\d+$/.test(rootStore.settings.serialMessage))
    ) {
      ipcRenderer.send('mainWindow->main->workerWindowNetwork-ticketById', [
        rootStore.settings.serialMessage,
      ]);
      return 0;
    }
    if (
      typeof onlineTicketResponse !== 'undefined' &&
      typeof result === 'string'
    ) {
      if (!onlineTicketResponse?.id) return 0;
      // We set the ticket from response
      const onlineTicket = onlineTicketResponse;
      console.log('Online ticket: ', onlineTicket);
      // Check if we have ever scanned before:
      const onlineTicketInState = rootStore.scannedTicketList.ticketById(
        onlineTicket?.id
      );
      console.log('onlineTicketInState', onlineTicketInState);
      console.log('onlineTicket?.id', onlineTicket?.id);

      // Set local state
      rootStore.ui.setLostTicketMode(false);
      rootStore.ui.setViewDetail(false);
      let localScannedTicket: ScannedTicket;
      // If it didn't exist in the state, create it
      let endTimeOnline = onlineTicket?.created + onlineTicket?.free_time;
      // If the ticket has been validated we add to the time
      if (onlineTicket?.state === 3 || onlineTicket?.state === 4) {
        console.log('ticket is validated');
        endTimeOnline =
          onlineTicket?.last_state_change + onlineTicket?.leave_time;
        onlineTicketInState?.setEndTime(endTimeOnline);
      }
      if (typeof onlineTicketInState === 'undefined') {
        localScannedTicket = new ScannedTicket({
          id: onlineTicket?.id, // This is very important here we save the entity with id of online ticket
          idTicket: getRandomInt(1000000000, 4294967295),
          version: -1,
          startType: 0,
          startTime: onlineTicket?.created,
          endType: 1,
          endTime: endTimeOnline,
          credits: 1,
          check: 'online ticket',
          qrData: result,
        });
        rootStore.scannedTicketList.add(localScannedTicket);
      } else if (
        typeof onlineTicketInState !== 'undefined' &&
        onlineTicketInState.credits === 1
      ) {
        // It exists, now we need to reuse the object in state
        localScannedTicket = onlineTicketInState;
      } else {
        // It exists, but credits are not === 1, now we need to reuse the object in state and trigger credit error
        localScannedTicket = onlineTicketInState;
        rootStore.ui.setCreditsError(true);
        return 1;
      }

      setScannedTicket(localScannedTicket);
      setTarif(rootStore.tarifList.all[0]);

      setStartTime(new Date(fromUnixTime(onlineTicket?.created)));
      setEndTime(new Date(fromUnixTime(endTimeOnline)));
      setState(
        compareAsc(new Date(), new Date(fromUnixTime(endTimeOnline))).toString()
      );

      // Return array with:
      // EndTime
      // Tarif
      // Ticket
      // Ticket credits unlimited
      return [
        fromUnixTime(endTimeOnline),
        rootStore.tarifList.all[0],
        localScannedTicket,
        0,
        false,
      ];
    }

    if (rootStore.scannedTicketList.useSimpleTicket) {
      const searchResult = result.search(
        rootStore.scannedTicketList.prefixSimpleTicket
      );
      if (searchResult !== -1) {
        const dataSimpleTicket: string = result.slice(searchResult);
        // Check if we have ever scanned before:
        const ticketInState =
          rootStore.scannedTicketList.simpleTicketById(dataSimpleTicket);
        // Set local state
        rootStore.ui.setLostTicketMode(false);
        rootStore.ui.setViewDetail(false);
        let localScannedTicketSimple: ScannedTicketSimple;
        // If it didn't exist in the state, create it
        if (typeof ticketInState === 'undefined') {
          localScannedTicketSimple = new ScannedTicketSimple({
            data: dataSimpleTicket,
          });
          rootStore.scannedTicketList.addSimple(localScannedTicketSimple);
          return 3;
        }
        // If it already exist it's already been used
        rootStore.ui.setCreditsError(true);
        return 1;
      }
    }

    let dataJSON;
    if (result) {
      try {
        dataJSON = JSON.parse(result);
      } catch (e) {
        console.log(e); // error in the above string (in this case, yes)!
        return 0;
      }
    }
    if (Array.isArray(dataJSON) === false) {
      return 0;
    }
    if (
      !dataJSON[0] &&
      !dataJSON[1] &&
      !dataJSON[2] &&
      !dataJSON[3] &&
      !dataJSON[4] &&
      !dataJSON[5] &&
      !dataJSON[6] &&
      !dataJSON[7]
    ) {
      return 0;
    }
    if (
      parseInt(dataJSON[6]) <
        rootStore.scannedTicketList.weightToSubstractCredits &&
      parseInt(dataJSON[6]) !== 0
    ) {
      return 0;
    }

    if (typeof parseInt(dataJSON[3]) !== 'number') return 0;
    if (typeof parseInt(dataJSON[5]) !== 'number') return 0;
    let unlimCreds = false;
    if (parseInt(dataJSON[6]) === 0) {
      unlimCreds = true;
    }

    // Check if we have ever scanned before:
    const ticketInState = rootStore.scannedTicketList.ticketByTicketId(
      parseInt(dataJSON[0])
    );
    // Set local state
    rootStore.ui.setLostTicketMode(false);
    rootStore.ui.setViewDetail(false);
    let localScannedTicket: ScannedTicket;
    // If it didn't exist in the state, create it
    if (typeof ticketInState === 'undefined') {
      localScannedTicket = new ScannedTicket({
        idTicket: parseInt(dataJSON[0]),
        version: parseInt(dataJSON[1]),
        startType: parseInt(dataJSON[2]),
        startTime: parseInt(dataJSON[3]),
        endType: parseInt(dataJSON[4]),
        endTime: parseInt(dataJSON[5]),
        credits: parseInt(dataJSON[6]),
        check: dataJSON[7],
        qrData: dataJSON.toString(),
      });
      rootStore.scannedTicketList.add(localScannedTicket);
    } else {
      // It exists, now we need to reuse the object in state
      localScannedTicket = ticketInState;
      // And check if it still has enough credits for at least one passage
      if (
        localScannedTicket.credits <
          rootStore.scannedTicketList.weightToSubstractCredits &&
        parseInt(dataJSON[6]) !== 0
      ) {
        // If it doesn't have enough we return and discard the ticket for this we use number 1 to return
        rootStore.ui.setCreditsError(true);
        return 1;
      }
    }
    if (parseInt(dataJSON[6]) !== 0) {
      rootStore.ui.setCreditsOnTicket(parseInt(dataJSON[6]));
    }
    console.log('localScannedTicket.credits', localScannedTicket.credits);
    setScannedTicket(localScannedTicket);

    // Actual check if the barcode is signed !!
    const localTemplateId =
      rootStore.templateList.returnTemplateForTicket(localScannedTicket);
    const localTemplate: Template | undefined =
      rootStore.templateList.getTemplateById(localTemplateId);
    // If it is not found, it doesn't exist
    if (typeof localTemplate === 'undefined') return 0;
    setTemplate(localTemplate);
    setTarif(rootStore.tarifList.getTarifById(localTemplate.idTarif));

    setStartTime(new Date(fromUnixTime(parseInt(dataJSON[3]))));
    setEndTime(new Date(fromUnixTime(parseInt(dataJSON[5]))));
    setState(
      compareAsc(
        new Date(),
        new Date(fromUnixTime(parseInt(dataJSON[5])))
      ).toString()
    );

    // Return array with:
    // EndTime
    // Tarif
    // Ticket
    // Ticket id
    return [
      fromUnixTime(parseInt(dataJSON[5])),
      rootStore.tarifList.getTarifById(localTemplate.idTarif),
      localScannedTicket,
      localScannedTicket.idTicket,
      unlimCreds,
    ];
  };

  // If nobody ever pays and emv is offline
  useEffect(() => {
    let timer: ReturnType<typeof setTimeout>;

    if (rootStore.ui.priceToPay !== -1) {
      timer = setTimeout(() => {
        rootStore.ui.setPriceToPay(-1);
      }, 300000);
    }
    return () => {
      clearTimeout(timer);
    };
  }, [rootStore.ui.priceToPay]);

  // Below is the main useEffect, it will listen to any changes on the serial
  useEffect(() => {
    let fetchedOnlineInfo: any;

    async function decodeAndGetPay() {
      // Below will return 0 for decoding error, 1 for not enough credits from existing scanned ticket,
      if (rootStore.ui.priceToPay !== -1) return;
      if (
        rootStore.settings.serialMessage === '' &&
        typeof fetchedOnlineInfo === 'undefined'
      )
        return;

      const returnFromDecode = await handleDecode(
        rootStore.settings.serialMessage,
        fetchedOnlineInfo
      );
      // Reset the fetchedData
      fetchedOnlineInfo = undefined;
      if (returnFromDecode === 3) {

        ipcRenderer.postMessage(
          'mainWindow->main->workerWindowNetwork-openPassage',
          rootStore.passageList.defaultPassageId,
          []
        );
        rootStore.ui.setEmvPaymentNotNeccessary(true);
        rootStore.ui.setPriceToPay(-1);
        setTimeout(() => {
          rootStore.ui.setEmvPaymentNotNeccessary(false);
        }, 10000);
        return;
      }
      if (returnFromDecode !== 0 && returnFromDecode !== 1) {
        const localPriceToPay = await checkPay(
          returnFromDecode[0],
          returnFromDecode[1]
        );
        const scannedTicketLocally: any = returnFromDecode[2];
        if (typeof localPriceToPay === 'number' && localPriceToPay >= 0) {
          rootStore.ui.setPriceToPay(-1);
        }
        if (localPriceToPay === 0) {
          // We change the amount of credits on the ticket
          if (returnFromDecode[4] === false) {
            scannedTicketLocally?.setCredits(
              scannedTicketLocally?.credits -
                rootStore.scannedTicketList.weightToSubstractCredits
            );
          }
          ipcRenderer.postMessage(
            'mainWindow->main->workerWindowNetwork-openPassage',
            rootStore.passageList.defaultPassageId,
            []
          );
          rootStore.ui.setEmvPaymentNotNeccessary(true);
          rootStore.ui.setPriceToPay(-1);
          setTimeout(() => {
            rootStore.ui.setEmvPaymentNotNeccessary(false);
          }, 10000);
          return;
        }
        rootStore.ui.setPriceToPay(localPriceToPay || -1);
        checkTime();
        checkDistanceWords();
        const scannedTktId = returnFromDecode[3];
        // Here we set the amount to pay
        const unlimCreds = returnFromDecode[4];
        const paymentId = await emvSendAmount(
          localPriceToPay,
          scannedTktId,
          unlimCreds
        );
      }
    }

    decodeAndGetPay();
    rootStore.settings.setSerialMessage('');

    ipcRenderer.on(
      'mainWindow->workerWindowNetwork-ticketById-reply',
      async (event, fetchedData) => {
        console.log('received ipc ', fetchedData);
        if (!fetchedData?.id) {
          rootStore.ui.setCreditsError(true);
          setTimeout(() => rootStore.ui.setCreditsError(false), 3000);
          return;
        }
        fetchedOnlineInfo = fetchedData;
        await decodeAndGetPay();
      }
    );

    return () => {
      ipcRenderer.removeAllListeners(
        'mainWindow->workerWindowNetwork-ticketById-reply'
      );
    };
  }, [rootStore.settings.serialMessage]);

  // Below to reset screen after message that ticket was already used because credits are done
  useEffect(() => {
    let timer: ReturnType<typeof setTimeout>;
    if (rootStore.ui.creditsError === true) {
      rootStore.ui.setCreditsError(true);
      timer = setTimeout(() => {
        rootStore.ui.setCreditsError(false);
      }, 3000);
    }
    return () => {
      clearTimeout(timer);
    };
  }, [rootStore.ui.creditsError]);

  const showStartTime = () => {
    let newDateObject;
    if (typeof scannedTicket?.startTime === 'number') {
      newDateObject = format(
        new Date(fromUnixTime(scannedTicket?.startTime)),
        'HH:mm:ss-dd/MM/yyyy'
      );
    }
    if (typeof newDateObject === 'undefined') {
      newDateObject = 'no valid date';
    }
    return newDateObject;
  };

  const showEndTime = () => {
    let newDateObject;
    if (typeof scannedTicket?.endTime === 'number') {
      newDateObject = format(
        new Date(fromUnixTime(scannedTicket?.endTime)),
        'HH:mm:ss-dd/MM/yyyy'
      );
    }
    if (typeof newDateObject === 'undefined') {
      newDateObject = 'no valid date';
    }
    return newDateObject;
  };

  const runFetchTriggerAux = async () => {
    if (typeof rootStore.acs01List?.defaultAcs01 === 'undefined') {
      return new Error();
    }
    const fetchData: any = await fetch(
      `http://${rootStore.acs01List?.defaultAcs01.localUrl}/apiv1/io_connection/${rootStore.auxList.defaultLostTicketOutputId}/action`,
      {
        method: 'POST',
        body: JSON.stringify({
          action: 3,
        }),
      }
    )
      .then((response: any) => {
        if (response.status !== 200) {
          return new Error(response.status);
        }
        return response.json();
      })
      .then((json: any) => {
        console.log('local', json);
        return json;
      })
      .catch((error) => {
        console.log('non local');
        return error;
      });
    return fetchData;
  };

  const triggerLostTicket = async () => {
    if (rootStore.terminal.scannerConnectedToDisplay) {
      rootStore.ui.setPriceToPay(parseInt(rootStore.terminal.lostTicketPrice));
      rootStore.ui.setLostTicketMode(true);
      const paymentId = await emvSendAmount(
        parseInt(rootStore.terminal.lostTicketPrice),
        0,
        false
      );
    } else {
      if (typeof rootStore.acs01List.defaultAcs01 === 'undefined') return;
      const triggerAux = await runFetchTriggerAux();
    }
  };

  const showButton = () => {
    if (rootStore.terminal.scannerConnectedToDisplay) {
      if (
        rootStore.ui.emvPaymentSuccess === true ||
        rootStore.ui.emvPaymentNotNeccessary === true
      ) {
        return false;
      }
      if (
        rootStore.passageList.actionState === 1 ||
        rootStore.passageList.actionState === 3
      ) {
        return false;
      }
      if (rootStore.ui.emvInitState === 2 && rootStore.ui.emvState === 2) {
        return false;
      }
      if (rootStore.ui.priceToPay !== -1) {
        return false;
      }
      return true;
    }
    if (
      rootStore.passageList.actionState === 1 ||
      rootStore.passageList.actionState === 3 ||
      rootStore.auxList.auxLostTicketActionState === 1 ||
      rootStore.auxList.auxLostTicketActionState === 3
    ) {
      return false;
    }
    return true;
  };

  const getText = () => {
    if (
      typeof rootStore.languageList.t1('Lost Ticket') === 'undefined' &&
      typeof rootStore.languageList.t2('Lost Ticket') !== 'undefined' &&
      typeof rootStore.languageList.t3('Lost Ticket') !== 'undefined'
    ) {
      return (
        <>
          <Typography variant="h3" noWrap>
            {rootStore.languageList.t2('Lost Ticket')}
          </Typography>
          <Typography style={{ marginLeft: 70 }} variant="h3" noWrap>
            {rootStore.languageList.t3('Lost Ticket')}
          </Typography>
        </>
      );
    }
    if (
      typeof rootStore.languageList.t1('Lost Ticket') === 'undefined' &&
      typeof rootStore.languageList.t2('Lost Ticket') === 'undefined' &&
      typeof rootStore.languageList.t3('Lost Ticket') !== 'undefined'
    ) {
      return (
        <Typography variant="h3" noWrap>
          {rootStore.languageList.t3('Lost Ticket')}
        </Typography>
      );
    }
    if (
      typeof rootStore.languageList.t1('Lost Ticket') === 'undefined' &&
      typeof rootStore.languageList.t2('Lost Ticket') === 'undefined' &&
      typeof rootStore.languageList.t3('Lost Ticket') === 'undefined'
    ) {
      return (
        <Typography variant="h3" noWrap>
          Please select a language in the settings
        </Typography>
      );
    }
    if (
      typeof rootStore.languageList.t1('Lost Ticket') !== 'undefined' &&
      typeof rootStore.languageList.t2('Lost Ticket') === 'undefined' &&
      typeof rootStore.languageList.t3('Lost Ticket') !== 'undefined'
    ) {
      return (
        <>
          <Typography variant="h3" noWrap>
            {rootStore.languageList.t1('Lost Ticket')}
          </Typography>
          <Typography style={{ marginLeft: 70 }} variant="h3" noWrap>
            {rootStore.languageList.t3('Lost Ticket')}
          </Typography>
        </>
      );
    }
    if (
      typeof rootStore.languageList.t1('Lost Ticket') !== 'undefined' &&
      typeof rootStore.languageList.t2('Lost Ticket') !== 'undefined' &&
      typeof rootStore.languageList.t3('Lost Ticket') === 'undefined'
    ) {
      return (
        <>
          <Typography variant="h3" noWrap>
            {rootStore.languageList.t1('Lost Ticket')}
          </Typography>
          <Typography style={{ marginLeft: 70 }} variant="h3" noWrap>
            {rootStore.languageList.t2('Lost Ticket')}
          </Typography>
        </>
      );
    }
    if (
      typeof rootStore.languageList.t1('Lost Ticket') === 'undefined' &&
      typeof rootStore.languageList.t2('Lost Ticket') !== 'undefined' &&
      typeof rootStore.languageList.t3('Lost Ticket') === 'undefined'
    ) {
      return (
        <Typography variant="h3" noWrap>
          {rootStore.languageList.t2('Lost Ticket')}
        </Typography>
      );
    }
    if (
      typeof rootStore.languageList.t1('Lost Ticket') === 'undefined' &&
      typeof rootStore.languageList.t2('Lost Ticket') !== 'undefined' &&
      typeof rootStore.languageList.t3('Lost Ticket') !== 'undefined'
    ) {
      return (
        <>
          <Typography variant="h3" noWrap>
            {rootStore.languageList.t2('Lost Ticket')}
          </Typography>
          <Typography style={{ marginLeft: 70 }} variant="h3" noWrap>
            {rootStore.languageList.t3('Lost Ticket')}
          </Typography>
        </>
      );
    }
    if (
      typeof rootStore.languageList.t1('Lost Ticket') !== 'undefined' &&
      typeof rootStore.languageList.t2('Lost Ticket') === 'undefined' &&
      typeof rootStore.languageList.t3('Lost Ticket') === 'undefined'
    ) {
      return (
        <Typography variant="h3" noWrap>
          {rootStore.languageList.t1('Lost Ticket')}
        </Typography>
      );
    }

    if (
      rootStore.languageList.t1('Lost Ticket') ===
      rootStore.languageList.t2('Lost Ticket')
    ) {
      return (
        <Typography variant="h3" noWrap>
          {rootStore.languageList.t1('Lost Ticket')}
        </Typography>
      );
    }
    if (
      rootStore.languageList.t2('Lost Ticket') ===
      rootStore.languageList.t3('Lost Ticket')
    ) {
      return (
        <>
          <Typography variant="h3" noWrap>
            {rootStore.languageList.t1('Lost Ticket')}
          </Typography>
          <Typography style={{ marginLeft: 70 }} variant="h3" noWrap>
            {rootStore.languageList.t2('Lost Ticket')}
          </Typography>
        </>
      );
    }
    if (
      rootStore.languageList.t1('Lost Ticket') ===
      rootStore.languageList.t3('Lost Ticket')
    ) {
      return (
        <>
          <Typography variant="h3" noWrap>
            {rootStore.languageList.t1('Lost Ticket')}
          </Typography>
          <Typography style={{ marginLeft: 70 }} variant="h3" noWrap>
            {rootStore.languageList.t2('Lost Ticket')}
          </Typography>
        </>
      );
    }
    return (
      <>
        <Typography variant="h3" noWrap>
          {rootStore.languageList.t1('Lost Ticket')}
        </Typography>
        <Typography style={{ marginLeft: 70 }} variant="h3" noWrap>
          {rootStore.languageList.t2('Lost Ticket')}
        </Typography>
        <Typography style={{ marginLeft: 70 }} variant="h3" noWrap>
          {rootStore.languageList.t3('Lost Ticket')}
        </Typography>
      </>
    );
  };

  return (
    <>
      {showButton() && rootStore.passageList.actionState !== 4 ? (
                <Grid item xs={12}>
          <Grid container justifyContent="center" spacing={0}>
            <Fab
              variant="extended"
              size="large"
              color="primary"
              aria-label="add"
              style={{
                margin: 50,
                paddingLeft: 150,
                paddingRight: 150,
                paddingTop: 50,
                paddingBottom: 50,
              }}
              // className={classes.buttonTicketLost}
              onClick={triggerLostTicket}
              onTouchStartCapture={triggerLostTicket}
            >
              {getText()}
            </Fab>
          </Grid>
        </Grid>
      ) : null}



    {/* CANCELLED SCREEN */}
    {rootStore.ui.emvTransactionCancelled && (
      <Grid container justifyContent="center" alignItems="center">
        <Grid item>
          <Paper elevation={3} className={classes.paperTopPay}>
            <Typography
              variant="h4"
              align="center"
              color="error"
              style={{ padding: 20 }}
            >
              {rootStore.languageList.t1('Transaction Cancelled') || 'Transaction Cancelled'}
            </Typography>
            <Typography
              variant="h6"
              align="center"
              style={{ marginTop: 10 }}
            >
              {rootStore.languageList.t1('Please try again') || 'Please try again'}
            </Typography>
          </Paper>
        </Grid>
      </Grid>
    )}
      {!showButton() &&
      rootStore.ui.priceToPay !== -1 &&
      rootStore.ui.viewDetail ? (
        <Grid
          item
          xs={12}
          sm={12}
          md={12}
          lg={12}
          className={classes.content}
          style={{ marginTop: 0 }}
        >
          <Timeline
            style={{ width: '150%', marginLeft: '-25%' }}
            align="alternate"
          >
            <TimelineItem style={{ width: '100%' }}>
              <TimelineOppositeContent style={{ width: '100%' }}>
                <Typography
                  className={classes.typoAddTicket}
                  style={{
                    color: rootStore.settings.darkMode ? 'white' : 'black',
                  }}
                  variant="h6"
                  color="textSecondary"
                >
                  {showStartTime().toString()}
                </Typography>
              </TimelineOppositeContent>
              <TimelineSeparator>
                <TimelineDot>
                  <TimeToLeave />
                </TimelineDot>
                <TimelineConnector style={{ height: 90 }} />
              </TimelineSeparator>
              <TimelineContent>
                <Paper elevation={3} className={classes.paper}>
                  <Typography variant="h6" component="h1">
                    {rootStore.languageList.t1('Entry time')}
                  </Typography>
                  <Typography>
                    {rootStore.languageList.t1('Start time ticket')}
                  </Typography>
                </Paper>
              </TimelineContent>
            </TimelineItem>
            {state === '-1' ? (
              <>
                <TimelineItem>
                  <TimelineOppositeContent>
                    <Typography
                      className={classes.typoAddTicket}
                      style={{
                        color: rootStore.settings.darkMode ? 'white' : 'black',
                        width: '100%',
                      }}
                      variant="h6"
                      color="textSecondary"
                    >
                      {time}
                    </Typography>
                  </TimelineOppositeContent>
                  <TimelineSeparator>
                    <TimelineDot color="primary">
                      <Timelapse />
                    </TimelineDot>
                    <TimelineConnector style={{ height: 90 }} />
                  </TimelineSeparator>
                  <TimelineContent>
                    <Paper elevation={3} className={classes.paper}>
                      <Typography variant="h6" component="h1">
                        {rootStore.languageList.t1('Current time')}
                      </Typography>
                      <Typography>
                        {rootStore.languageList.t1('The current date and time')}
                      </Typography>
                    </Paper>
                  </TimelineContent>
                </TimelineItem>
                <TimelineItem>
                  <TimelineOppositeContent>
                    <Typography
                      className={classes.typoAddTicket}
                      style={{
                        color: rootStore.settings.darkMode ? 'white' : 'black',
                      }}
                      variant="h6"
                      color="textSecondary"
                    >
                      {showEndTime().toString()} ({checkDistanceWords()} left)
                    </Typography>
                  </TimelineOppositeContent>
                  <TimelineSeparator>
                    <TimelineDot color="secondary">
                      <Schedule />
                    </TimelineDot>
                  </TimelineSeparator>
                  <TimelineContent>
                    <Paper elevation={3} className={classes.paper}>
                      <Typography
                        variant="h6"
                        component="h1"
                        style={{ width: '100%' }}
                      >
                        {rootStore.languageList.t1('Free exit time')}
                      </Typography>
                      <Typography>
                        {rootStore.languageList.t1('End of free time ticket')}
                      </Typography>
                      <Typography>
                        {rootStore.languageList.t1('Time left:')}
                        {checkDistanceWords()}
                      </Typography>
                    </Paper>
                  </TimelineContent>
                </TimelineItem>
              </>
            ) : (
              <>
                <TimelineItem>
                  <TimelineOppositeContent>
                    <Typography
                      className={classes.typoAddTicket}
                      style={{
                        color: rootStore.settings.darkMode ? 'white' : 'black',
                        width: '100%',
                      }}
                      variant="h6"
                      color="textSecondary"
                    >
                      {showEndTime().toString()} ({checkDistanceWords()} ago)
                    </Typography>
                  </TimelineOppositeContent>
                  <TimelineSeparator>
                    <TimelineDot color="secondary">
                      <Schedule />
                    </TimelineDot>
                    <TimelineConnector style={{ height: 90 }} />
                  </TimelineSeparator>
                  <TimelineContent>
                    <Paper
                      elevation={3}
                      className={classes.paper}
                      style={{ marginLeft: -10 }}
                    >
                      <Typography
                        style={{ width: '100%' }}
                        variant="h6"
                        component="h1"
                      >
                        {rootStore.languageList.t1('Free exit time')}
                      </Typography>
                      <Typography>
                        {rootStore.languageList.t1('End time ticket')}
                      </Typography>
                    </Paper>
                  </TimelineContent>
                </TimelineItem>
                <TimelineItem>
                  <TimelineOppositeContent>
                    <Typography
                      className={classes.typoAddTicket}
                      style={{
                        color: rootStore.settings.darkMode ? 'white' : 'black',
                      }}
                      variant="h6"
                      color="textSecondary"
                    >
                      {time}
                    </Typography>
                  </TimelineOppositeContent>
                  <TimelineSeparator>
                    <TimelineDot color="primary">
                      <Timelapse />
                    </TimelineDot>
                  </TimelineSeparator>
                  <TimelineContent>
                    <Paper elevation={3} className={classes.paper}>
                      <Typography variant="h6" component="h1">
                        {rootStore.languageList.t1('Current time')}
                      </Typography>
                      <Typography>
                        {rootStore.languageList.t1('Time inside parking: ')}
                        {checkDistanceHoursMinutes()}
                      </Typography>
                      <Typography>
                        {rootStore.languageList.t1('Price to pay: € ')}
                        {rootStore.ui.priceToPay}
                      </Typography>
                    </Paper>
                  </TimelineContent>
                </TimelineItem>
              </>
            )}
            
          </Timeline>
          
        </Grid>
      ) : null}
      
    </>
  );
}

export default observer(HomeContentBottomExitPayInLaneDatacap);
