/* eslint-disable react/jsx-key */
/* eslint-disable compat/compat */
/* eslint-disable radix */
import React, { useEffect, useState } from "react";
import {
  Grid,
  Paper,
  Typography,
  Fab,
  TextField,
} 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 Timeline from "@mui/lab/Timeline";
import TimelineItem from "@mui/lab/TimelineItem";
import TimelineOppositeContent from "@mui/lab/TimelineOppositeContent";
import TimelineSeparator from "@mui/lab/TimelineSeparator";
import TimelineDot from "@mui/lab/TimelineDot";
import TimelineConnector from "@mui/lab/TimelineConnector";
import TimelineContent from "@mui/lab/TimelineContent";
import Timelapse from "@mui/icons-material/Timelapse";
import TimeToLeave from "@mui/icons-material/TimeToLeave";
import Schedule from "@mui/icons-material/Schedule";
import { decode } from "punycode";
import { useNavigate } from "react-router-dom";
import { ipcRenderer } from "electron";
import ScannedTicket from "../../models/Application/ScannedTicket";
import Arrow from "../../assets/images/ArrowRightCAME200.png";
import PayOnFoot from "../../assets/images/PayOnFoot200.png";
import BasketView from "../views/BasketView";
import TicketModelListView from "../views/TicketModelListView";
import AddTicketModelView from "../views/AddTicketModelView";
import { getRootStore } from "../../models/root-store.ts";
import Tarif from "../../models/Application/Tarif";
import Template from "../../models/Application/Template";
import HomeContentTopPayOnFoot from "./HomeContentTopPayOnFoot";
import HomeContentTopVirtualPrinter from "./HomeContentTopVirtualPrinter";
import ScannedTicketSimple from "../../models/Application/ScannedTicketSimple";
import Log from "../../models/Logs/Log";

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",
    marginTop: -80,
    "@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",
    },
  },
  animatedItem: {
    zIndex: 2,
    marginTop: 170,
    animation: `$myEffect 3000ms infinite alternate`,
  },
  "@keyframes myEffect": {
    "100%": {
      zIndex: 2,
      opacity: 1,
      transform: "translateX(23%)",
    },
    "0%": {
      zIndex: 2,
      opacity: 1,
      transform: "translateX(-45%)",
    },
  },
  animatedItemPay: {
    zIndex: 2,
    marginTop: 170,
    animation: `$myEffectPay 5000ms infinite alternate`,
  },
  "@keyframes myEffectPay": {
    "100%": {
      opacity: 1,
      transform: "translateX(55%)",
    },
    "0%": {
      opacity: 1,
      transform: "translateX(-45%)",
    },
  },
  zoomedItem: {
    overflow: "hidden",
  },
  animatedItemPayZoom: {
    animation: `$myEffectPayZoom 5000ms infinite alternate ease-in-out`,
    zIndex: 1,
  },
  "@keyframes myEffectPayZoom": {
    "100%": {
      zIndex: 1,
      opacity: 1,
      transform: "scale(1.5)",
    },
    "0%": {
      zIndex: 1,
      opacity: 1,
      transform: "scale(1)",
    },
  },
});
const succesFetch = false;
const tries = 0;

const HomeContentBottomPayOnFoot = () => {
  const [rootStore] = useState(() => getRootStore());
  const classes = useStyles();
  const [qrTextField, setQrTextField] = useState<string>("");
  const [data, setData] = React.useState("No ticket scanned");
  const [state, setState] = React.useState("nothing");
  const [scannedTicket, setScannedTicket] = React.useState<ScannedTicket>();
  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 [distance, setDistance] = React.useState("");
  const [distanceSeconds, setDistanceSeconds] = React.useState<number>();
  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(url: string) {
    if (typeof url === "undefined") {
      return new Error("No URL for EMV");
    }
    const fetchData = await fetch(url, {
      method: "GET",
    })
      .then((response) => {
        if (response.status !== 200) {
          return new Error(response.status.toString());
        }
        return response.json();
      })
      .then((json) => {
        return json;
      })
      .catch((error) => {
        return new Error(error);
      });
    return fetchData;
  }
  // We will run below to check if the staet of the payment changes (interval in useEffect when we launch payment)
  const getCurrentPaymentState = async () => {
    // 1 for not busy, 2 for asking money
    const getPaymentState = await fetchEmv(
      `http://${rootStore.settings.ipEMV}:7777/PayEngineService/GetCurrentPaymentState`
    );
    if (getPaymentState === 1 || getPaymentState === 2) {
      rootStore.ui.setEmvState(getPaymentState);
      if (getPaymentState === 1) {
        rootStore.ui.setPriceToPay(-1);
        // setEmvCommandSend(false);
        return getPaymentState;
      }
      return getPaymentState;
    }
    return getPaymentState;
  };

  const getCurrentPaymentStateInitial = async () => {
    try {
      const unlockPayTerminal = await fetchEmv(
        `http://${rootStore.settings.ipEMV}:7777/PayTerminalService/UnlockPayTerminal`
      );
      console.log("INIT_1_ unlockPayTerminal: ", unlockPayTerminal);
      // Lock payterminal
      const lockPayTerminal = await fetchEmv(
        `http://${rootStore.settings.ipEMV}:7777/PayTerminalService/LockPayTerminal`
      );
      console.log("INIT_2_ lockPayTerminal: ", lockPayTerminal);

      // 1 for not busy, 2 for asking money
      const getPaymentState = await fetchEmv(
        `http://${rootStore.settings.ipEMV}:7777/PayEngineService/GetCurrentPaymentState`
      );
      console.log("INIT_3_ getPaymentState: ", getPaymentState);

      if (getPaymentState === 1 || getPaymentState === 2) {
        rootStore.ui.setEmvState(getPaymentState);
        if (getPaymentState === 1) {
          rootStore.ui.setPriceToPay(-1);
          // setEmvCommandSend(false);
          return getPaymentState;
        }
        return getPaymentState;
      }
      return getPaymentState;
    } catch (error) {
      return console.log("error while fetching from EMV");
    }
  };

  // We will run below to check how much we successfully debited (interval in useEffect when we launch payment)
  const getCurrentAmountDebited = async (
    unlimCreds: any,
    fetchedOnlineInfo: any
  ) => {
    if (rootStore.ui.priceToPay === -1) return;
    if (rootStore.ui.priceToPay === 0) return;
    if (rootStore.ui.emvPaymentId === "") return;

    const valueSend = rootStore.ui.priceToPay * 100;
    const valueSendWithoutComma = parseInt(valueSend.toFixed(0));

    // 1 for not busy, 2 for asking money
    const getPaymentAmountDone = await fetchEmv(
      `http://${
        rootStore.settings.ipEMV
      }:7777/PayEngineService/GetAmountDebited?${new URLSearchParams({
        paymentTransactionID: `${rootStore.ui.emvPaymentId}`,
      })}`
    );
    if (getPaymentAmountDone === valueSendWithoutComma) {
      if (typeof fetchedOnlineInfo !== "undefined") {
        // Set the state of the online ticket to 4
        // Then we now it has been payed
        ipcRenderer.postMessage(
          "mainWindow->main->workerWindowNetwork-changeOnlineTicketState",
          fetchedOnlineInfo.id,
          []
        );
      }
      // Now we have payed
      // We change the amount of credits on the ticket
      if (unlimCreds === false) {
        scannedTicket?.setCredits(
          scannedTicket?.credits -
            rootStore.scannedTicketList.weightToSubstractCredits
        );
      }
      rootStore.ui.setEmvPaymentSuccess(true);
      rootStore.ui.setViewCancel(false);
      /*
      ipcRenderer.postMessage(
        "mainWindow->main->workerWindowNetwork-openPassage",
        rootStore.passageList.defaultPassageId,
        []
      );
      */
      rootStore.ui.setPriceToPay(-1);

      setTimeout(() => {
        rootStore.ui.setEmvPaymentSuccess(false);
      }, 10000);
    } else {
      rootStore.ui.setEmvPaymentSuccess(false);
    }
  };

  const emvSendAmount = async (amount: number) => {
    // if (emvCommandSend) return;

    const valueToSend = amount * 100;
    const valueToSendWithoutComma = valueToSend.toFixed(0);
    // UnLock payterminal
    // setEmvCommandSend(true);
    try {
      const unlockPayTerminal = await fetchEmv(
        `http://${rootStore.settings.ipEMV}:7777/PayTerminalService/UnlockPayTerminal`
      );
      console.log("1_ unlockPayTerminal: ", unlockPayTerminal);

      // Lock payterminal
      const lockPayTerminal = await fetchEmv(
        `http://${rootStore.settings.ipEMV}:7777/PayTerminalService/LockPayTerminal`
      );
      console.log("2_ lockPayTerminal: ", lockPayTerminal);

      // Release payengine
      const releasePayEngine = await fetchEmv(
        `http://${rootStore.settings.ipEMV}:7777/PayEngineService/ReleasePayEngine`
      );
      console.log("3_ releasePayEngine: ", releasePayEngine);

      // Init payengine
      const initPayEngine = await fetchEmv(
        `http://${rootStore.settings.ipEMV}:7777/PayEngineService/InitPayEngine`
      );
      console.log("4_ initPayEngine: ", initPayEngine);

      // Send payengine
      const sendPayEngine = await fetchEmv(
        `http://${
          rootStore.settings.ipEMV
        }:7777/PayEngineService/Debit?${new URLSearchParams({
          amount: `${valueToSendWithoutComma}`,
        })}`
      );

      console.log("5_ sendPayEngine: ", sendPayEngine);
      if (sendPayEngine !== "") {
        rootStore.ui.setEmvPaymentId(sendPayEngine);
        // rootStore.settings.setStateEmv(true);
        console.log("6_ SUCCESS !!!", sendPayEngine);
        // Below will contain the id of the payment
        return sendPayEngine;
      }
      return "";
    } catch (error) {
      console.error("error while fetching from EMV");
      return "";
      // expected output: ReferenceError: nonExistentFunction is not defined
      // Note - error messages will vary depending on browser
    }
  };

  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") {
      return 0;
    }
    if (
      typeof onlineTicketResponse === "undefined" &&
      regexExp.test(rootStore.settings.serialMessage) === true
    ) {
      ipcRenderer.send("mainWindow->main->workerWindowNetwork-ticketById", [
        rootStore.settings.serialMessage,
      ]);
      return 0;
    }
    if (
      typeof onlineTicketResponse !== "undefined" &&
      typeof result === "string"
    ) {
      // We set the ticket from response
      const onlineTicket = onlineTicketResponse;
      // Check if we have ever scanned before:
      const onlineTicketInState = rootStore.scannedTicketList.ticketById(
        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) {
        endTimeOnline =
          onlineTicket?.last_state_change + onlineTicket?.leave_time;
      }
      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],
        0,
        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);
    const localTemplateId =
      rootStore.templateList.returnTemplateForTicket(localScannedTicket);
    const localTemplate: Template | undefined =
      rootStore.templateList.getTemplateById(localTemplateId);
    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,
    ];
  };

  // To get the state of EMV on first render
  useEffect(() => {
    let interVal: ReturnType<typeof setInterval>;
    (async () => {
      try {
        const initStateEmv = await getCurrentPaymentStateInitial();
        if (initStateEmv === 1 || initStateEmv === 2) {
          rootStore.ui.setEmvInitState(initStateEmv);
        }
        if (initStateEmv === 2) {
          interVal = setInterval(async () => {
            const stateEmv = await getCurrentPaymentState();
            if (stateEmv === 1) {
              rootStore.ui.setPriceToPay(-1);
              clearInterval(interVal);
            }
          }, 2000);
        }
      } catch (error) {
        console.log(error);
      }
    })();
    return () => {
      clearInterval(interVal);
    };
  }, []);

  // 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);
      }, 40000);
    }
    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() {
      let interVal: ReturnType<typeof setInterval>;

      // Below will return 0 for decoding error, 1 for not enough credits from existing scanned ticket,
      // 3 is a simple ticket
      //
      if (rootStore.ui.priceToPay !== -1) return;
      if (
        rootStore.settings.serialMessage === "" &&
        typeof fetchedOnlineInfo === "undefined"
      )
        return;

      const returnFromDecode = await handleDecode(
        rootStore.settings.serialMessage,
        fetchedOnlineInfo
      );

      // If we get 3 we have a good simpleTicket scanned
      if (returnFromDecode === 3) {
        // We change the amount of credits on the ticket
        /*
        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;
      }
      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 && returnFromDecode[3] !== 0) {
            /*
            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
        if (typeof localPriceToPay !== "undefined") {
          const paymentId = await emvSendAmount(localPriceToPay);
          if (paymentId !== "") {
            console.log("______--__ paymentId", paymentId);
            interVal = setInterval(() => {
              console.log("the interval is now running");
              getCurrentPaymentState();
              getCurrentAmountDebited(returnFromDecode[4], fetchedOnlineInfo);
              if (rootStore.ui.priceToPay === -1) {
                rootStore?.logs.addLog(
                  new Log({
                    type: "Application",
                    subType: "EMV",
                    name: "Payment of a ticket successful",
                    reason: `From ticket: ${returnFromDecode[3]}, payment id: ${paymentId}, price: € ${localPriceToPay}`, // returnFromDecode[2] is the ticket id after decoding the ticket
                    user: "System",
                  })
                );
                clearInterval(interVal);
              }
            }, 2000);
          }
        }
      }
    }
    // Reset the fetchedData
    fetchedOnlineInfo = undefined;

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

    ipcRenderer.on(
      "mainWindow->workerWindowNetwork-ticketById-reply",
      async (event, fetchedData) => {
        console.log("received ipc ", fetchedData);
        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 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)
      );
      if (paymentId !== "") {
        const interVal = setInterval(() => {
          getCurrentPaymentState();
          getCurrentAmountDebited(false, undefined);
          if (rootStore.ui.priceToPay === -1) {
            rootStore?.logs.addLog(
              new Log({
                type: "Application",
                subType: "EMV",
                name: "Payment of a lost ticket successful",
                reason: `From a lost ticket, payment id: ${paymentId}, price: € ${rootStore.terminal.lostTicketPrice}`, // returnFromDecode[2] is the ticket id after decoding the ticket
                user: "System",
              })
            );
            rootStore.ui.setLostTicketMode(false);
            clearInterval(interVal);
          }
        }, 2000);
      }
    } else {
      // 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.ui.emvPaymentSuccess &&
      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">
                      Entry time
                    </Typography>
                    <Typography>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">
                          Current time
                        </Typography>
                        <Typography>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%" }}
                        >
                          Free exit time
                        </Typography>
                        <Typography>End of free time ticket</Typography>
                        <Typography>
                          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"
                        >
                          Free exit time
                        </Typography>
                        <Typography>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">
                          Current time
                        </Typography>
                        <Typography>
                          Time inside parking: {checkDistanceHoursMinutes()}
                        </Typography>
                        <Typography>
                          Price to pay: € {rootStore.ui.priceToPay}
                        </Typography>
                      </Paper>
                    </TimelineContent>
                  </TimelineItem>
                </>
              )}
            </Timeline>
          </Grid>
        </>
      ) : null}
      {!rootStore.ui.emvPaymentSuccess &&
      rootStore.ui.priceToPay !== -1 &&
      !rootStore.ui.viewDetail ? (
        <Grid item xs={12}>
          <Paper
            elevation={3}
            className={classes.paperTopPayContent}
            style={{ background: "#DADADA" }}
          >
            <Grid container justifyContent="center" spacing={0}>
              <div className={classes.animatedItemPay}>
                <img src={Arrow} height="112pt" alt="" />
              </div>
              <div className={classes.zoomedItem}>
                <img
                  className={classes.animatedItemPayZoom}
                  src={PayOnFoot}
                  alt=""
                />
              </div>
            </Grid>
          </Paper>
        </Grid>
      ) : null}
      {!rootStore.ui.emvPaymentSuccess &&
      rootStore.ui.priceToPay === -1 &&
      !rootStore.ui.emvPaymentNotNeccessary ? (
        <Grid item xs={12}>
          <Paper
            elevation={3}
            className={classes.paperTopPayContent}
            style={{ background: "#DADADA" }}
          >
            <Grid container justifyContent="center" spacing={0}>
              <div className={classes.animatedItem}>
                <img src={Arrow} height="112pt" alt="" />
              </div>
              <img src={PayOnFoot} alt="" />
            </Grid>
          </Paper>
        </Grid>
      ) : null}
    </>
  );
};

export default observer(HomeContentBottomPayOnFoot);
