/* eslint-disable react/jsx-key */
import { observer } from 'mobx-react';
import React, { useEffect, useState } from 'react';
import {
  Box,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableRow,
  Typography,
} from '@mui/material';
import { QRCode } from 'react-qr-svg';

import { ipcRenderer } from 'electron';
import { format, fromUnixTime } from 'date-fns';

import stw from 'spread-the-word';
import { Validator } from 'ip-num';
import { getRootStore } from '../../../models/root-store';

const applicationType = [
  { id: 0, name: 'Virtual printer' },
  { id: 1, name: 'Entry unit' },
  { id: 2, name: 'Exit unit' },
  { id: 3, name: 'Pay on foot' },
  { id: 4, name: 'Pay in lane, entry' },
  { id: 5, name: 'Pay in lane, exit' },
  { id: 6, name: 'Counter dashboard' },
];

function PrintEngine() {
  const [rootStore] = useState(() => getRootStore());
  const [basket, setBasket] = useState<any>([]);
  const [betaalbewijs, setBetaalbewijs] = useState<any>();
  const amount = betaalbewijs?.amount || 0;
  const btwAfterComma = betaalbewijs?.btw / 100;
  const btwBetaalbewijs = amount * btwAfterComma;

  

  useEffect(() => {
    const timer = setTimeout(() => {
      ipcRenderer.postMessage('closeWorkerQr', [], []);
    }, 600000);
    /*
    (async () => {
      await autoDiscover();
    })();
    */
    // autoDiscoverApps();
    return () => {
      clearTimeout(timer);
    };
  }, []);

  useEffect(() => {
    ipcRenderer.on('workerDoneLoadingConfirm', (event, result) => {
      setBasket([]);
      setBetaalbewijs('');
    });
    return () => {
      ipcRenderer.removeAllListeners('workerDoneLoadingConfirm');
    };
  }, []);

  const euroOfDollar = (betaalb: any) => {
    if (betaalb.lang === 'US') return '$';
    return '€';
  };
            
  return (
    <>
      {
        // Use below to debug and see the complete snapshot
        /*
        <>
          <h5>SNAPSHOT</h5>
          <pre style={{ fontSize: 10, whiteSpace: "pre-wrap" }}>
            {rootStore.printerList.printerState}
          </pre>
        </>
        */
      }
      {amount !== 0 ? (
        <>
          <Typography
            variant="h5"
            component="h5"
            className="text"
            style={{
              font: 'Courier',
              fontSize: 22,
              color: 'black',
              fontWeight: 'bold',
              marginBottom: 10,
            }}
          >
            {betaalbewijs?.title}
          </Typography>
          <Typography
            variant="body1"
            className="text"
            style={{
              font: 'Courier',
              color: 'black',
              fontWeight: 'bold',
              marginBottom: 10,
            }}
          >
            {euroOfDollar(betaalbewijs) === '€'
              ? format(new Date(), 'HH:mm:ss-dd/MM/yyyy')
              : format(new Date(), 'HH:mm:ss-MM/dd/yyyy')}
          </Typography>
          <Typography
            variant="body1"
            className="text"
            style={{
              font: 'Courier',
              color: 'black',
              fontWeight: 'bold',
              marginBottom: 10,
            }}
          >
            {betaalbewijs?.itemText}
          </Typography>
          <TableContainer>
            <Table sx={{ maxWidth: 50, marginLeft: -1 }}>
              <TableBody>
                <TableRow
                  key="received"
                  sx={{
                    '&:last-child td, &:last-child th': {
                      border: 0,
                      heigth: 10,
                    },
                  }}
                >
                  <TableCell sx={{ color: 'black' }} size="small" scope="row">
                    {euroOfDollar(betaalbewijs) === '€'
                      ? 'Ontvangen:'
                      : 'Received:'}
                  </TableCell>
                  <TableCell
                    sx={{ color: 'black', width: 30 }}
                    size="small"
                    align="right"
                  >
                    {`${euroOfDollar(betaalbewijs)}${betaalbewijs?.amount}`}
                  </TableCell>
                </TableRow>
                <TableRow
                  key="net"
                  sx={{
                    '&:last-child td, &:last-child th': {
                      border: 0,
                    },
                  }}
                >
                  <TableCell sx={{ color: 'black' }} scope="row">
                    Netto:
                  </TableCell>
                  <TableCell sx={{ color: 'black' }} align="right">
                    {`${euroOfDollar(betaalbewijs)}${amount - btwBetaalbewijs}`}
                  </TableCell>
                </TableRow>
                <TableRow
                  key="btw"
                  sx={{
                    '&:last-child td, &:last-child th': {
                      border: 0,
                    },
                  }}
                >
                  <TableCell sx={{ color: 'black' }} scope="row">
                    {betaalbewijs?.btw}%
                    {euroOfDollar(betaalbewijs) === '€' ? 'BTW:' : 'VAT:'}
                  </TableCell>
                  <TableCell sx={{ color: 'black' }} align="right">
                    {`${euroOfDollar(betaalbewijs)}${btwBetaalbewijs}`}
                  </TableCell>
                </TableRow>
                <TableRow
                  key="total"
                  sx={{
                    '&:last-child td, &:last-child th': {
                      border: 0,
                    },
                  }}
                >
                  <TableCell sx={{ color: 'black' }} scope="row">
                    {euroOfDollar(betaalbewijs) === '€' ? 'Totaal:' : 'Total:'}
                  </TableCell>
                  <TableCell sx={{ width: 400, color: 'black' }} align="right">
                    {`${euroOfDollar(betaalbewijs)}${betaalbewijs?.amount}`}
                  </TableCell>
                </TableRow>
              </TableBody>
            </Table>
          </TableContainer>
          <Typography
            variant="body2"
            className="text"
            style={{
              font: 'Courier',
              color: 'black',
              fontWeight: 'bold',
              marginBottom: 5,
            }}
          >
            {euroOfDollar(betaalbewijs) === '€'
              ? 'Betaalmethode:'
              : 'Payment method:'}
            {`${betaalbewijs?.method}`}
          </Typography>

          <Typography
            variant="body1"
            className="text"
            style={{
              font: 'Courier',
              color: 'black',
              fontWeight: 'bold',
            }}
          >
            {betaalbewijs?.goodBy}
          </Typography>
        </>
      ) : null}

      {Array.isArray(basket)
        ? basket.map((ticket) => (
            <div key={ticket.id}>
              <Box
                display="flex"
                flexDirection="column"
                alignItems="center"
                justifyContent="center"
                alignContent="center"
                alignSelf="center"
                width={260}
                marginLeft={0}
              >
                <Typography
                  variant="h5"
                  component="h5"
                  className="text"
                  style={{
                    font: 'Courier',
                    fontSize: 22,
                    color: 'black',
                    fontWeight: 'bold',
                  }}
                >
                  {ticket.title}
                </Typography>
                <Typography
                  variant="h6"
                  style={{
                    marginTop: 10,
                    font: 'Courier',
                    color: 'black',
                    fontSize: 18,
                  }}
                  component="h6"
                  className="text"
                >
                  {ticket.subtitle}
                </Typography>
                <Typography
                  variant="body1"
                  component="p"
                  align="center"
                  style={{
                    marginTop: 10,
                    font: 'Courier',
                    color: 'black',
                    fontSize: 16,
                  }}
                  className="text"
                >
                  {ticket.text}
                </Typography>
                <QRCode
                  bgColor="#FFFFFF"
                  fgColor="#000000"
                  level="M"
                  style={{ marginTop: 10, width: '20mm' }}
                  value={ticket.qrData}
                />
                <Typography
                  variant="body1"
                  component="span"
                  className="textStartTime"
                  style={{
                    font: 'Courier',
                    color: 'black',
                    fontSize: 11,
                    height: '40px',
                    marginTop: 10,
                    marginBottom: 20,
                  }}
                >
                  {format(
                    new Date(fromUnixTime(parseInt(ticket.startTime, 10))),
                    'HH:mm:ss-dd/MM/yyyy'
                  )}
                  {' --> '}
                  {format(
                    new Date(fromUnixTime(parseInt(ticket.endTime, 10))),
                    'HH:mm:ss-dd/MM/yyyy'
                  )}
                </Typography>
              </Box>
              <div style={{ marginTop: 20, pageBreakAfter: 'always' }} />
            </div>
          ))
        : null}
    </>
  );
}

export default observer(PrintEngine);
