/* eslint-disable consistent-return */
/* 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,
  fromUnixTime,
} from "date-fns";
import { observer } from "mobx-react";
import SerialPort from "serialport";
import TicketModelListView from "../views/TicketModelListView";
import AddTicketModelView from "../views/AddTicketModelView";
import { getRootStore } from "../../models/root-store.ts";
import Template from "../../models/Application/Template";

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 ConfigureTicketTemplates = () => {
  const [rootStore] = useState(() => getRootStore());
  const classes = useStyles();
  const [template, setTemplate] = React.useState<Template>();
  const [endTime, setEndTime] = useState<Date>();

  const fetchWithTimeout: any = async (
    url: string,
    timeout: number,
    retries: number
  ) => {
    const ctrl = new AbortController();
    const { signal } = ctrl;
    console.log(`${url} ${retries}`);

    const fetchData: any = fetch(url, { signal })
      .then((response) => {
        // exclude 4xx and 5xx status codes
        if (response.status >= 200 && response.status <= 299) {
          return response.json();
        }
        if (retries > 0) {
          return fetchWithTimeout(url, timeout, retries - 1);
        }
        throw new Error(response.status.toString());
      })
      .catch((error) => {
        throw error;
      }); // sent error stack trace
    // set timeout
    const timeOut = new Promise((resolve, reject) => {
      setTimeout(async () => {
        ctrl.abort(); // abort fetch request
        reject(Error());
        return Error();
      }, timeout);
    });

    try {
      const result = await Promise.race([fetchData, timeOut]);
      return result;
    } catch (err) {
      if (retries > 0) {
        return fetchWithTimeout(url, timeout, retries - 1);
      }
    }
  };

  const emvSendAmount = async (amount: number) => {
    // UnLock payterminal
    const unlockPayTerminal = await fetchWithTimeout(
      "http://192.168.201.20:7777/PayTerminalService/UnlockPayTerminal",
      800,
      1
    );
    console.log("unlockPayTerminal: ", unlockPayTerminal);

    // Lock payterminal
    const lockPayTerminal = await fetchWithTimeout(
      "http://192.168.201.20:7777/PayTerminalService/LockPayTerminal",
      800,
      1
    );
    console.log("lockPayTerminal: ", lockPayTerminal);

    // Release payengine
    const releasePayEngine = await fetchWithTimeout(
      "http://192.168.201.20:7777/PayEngineService/ReleasePayEngine",
      5000,
      3
    );
    console.log("releasePayEngine: ", releasePayEngine);

    // Init payengine
    const initPayEngine = await fetchWithTimeout(
      "http://192.168.201.20:7777/PayEngineService/InitPayEngine",
      2000,
      1
    );
    console.log("initPayEngine: ", initPayEngine);

    // Send payengine
    const sendPayEngine = await fetchWithTimeout(
      `http://192.168.201.20:7777/PayEngineService/Debit?${new URLSearchParams({
        amount: `${amount}`,
      })}`,
      800,
      1
    );
    console.log("sendPayEngine: ", sendPayEngine);

    Promise.all([
      unlockPayTerminal,
      lockPayTerminal,
      releasePayEngine,
      initPayEngine,
      sendPayEngine,
    ])
      .then((result) => {
        // console.log(`Results in promises ${result}`);
        rootStore.ui.setViewCancel(true);
        return result;
      })
      .then((json) => json)
      .catch((error) => {
        rootStore.ui.setViewCancel(false);
        return console.log(`Error in promises ${error}`);
      });
  };

  useEffect(() => {
    const timer = setTimeout(() => {
      rootStore.ui.setViewCancel(true);
      if (rootStore.ui.lostTicketMode === true) {
        rootStore.ui.setPriceToPay(-1);
        rootStore.ui.setLostTicketMode(false);
      }
    }, 15000);
    return () => clearTimeout(timer);
  });

  const onClickEventLostTicket = async (e: any) => {
    e.preventDefault();
    const ticketPrice = rootStore.ticketList.getTicketById(
      rootStore.settings.lostTicketId
    )?.price;
    if (typeof ticketPrice === "number") {
      rootStore.ui.setPriceToPay(ticketPrice);
      emvSendAmount(ticketPrice);
    } else {
      return;
    }
    rootStore.ui.setViewCancel(false);
    rootStore.ui.setLostTicketMode(true);
    rootStore.ui.setViewDetail(false);
  };

  return (
    <>
      <Grid container spacing={0}>
        {rootStore.userList.loggedInUser &&
        rootStore.userList.loggedInUser.userlevel <= 1 ? (
          <Grid item xs={12} className={classes.content}>
            <Paper
              elevation={3}
              className={classes.paperTop}
              style={{ background: "#61728E85" }}
            >
              <AddTicketModelView
                ticketList={rootStore.ticketList}
                basket={rootStore.basket}
              />
            </Paper>
          </Grid>
        ) : null}
        <Grid item xs={12}>
          <Paper
            elevation={3}
            className={classes.paper}
            style={{ background: `${rootStore.settings.backgroundColor}` }}
          >
            <Grid container justifyContent="center" spacing={0}>
              <TicketModelListView
                ticketList={rootStore.ticketList}
                basket={rootStore.basket}
              />
            </Grid>
          </Paper>
        </Grid>
      </Grid>
    </>
  );
};

export default observer(ConfigureTicketTemplates);
