/* eslint-disable react/jsx-no-useless-fragment */
/* eslint-disable react/jsx-key */
/* eslint-disable react/destructuring-assignment */
/* eslint-disable compat/compat */
/* eslint-disable react/jsx-props-no-spreading */
import React, { useState } from 'react';
import {
  Grid,
  Paper,
  TextField,
  Button,
  FormControl,
  Switch,
  Autocomplete,
} from '@mui/material';
import { makeStyles } from '@mui/styles';
import Typography from '@mui/material/Typography';
import { observer } from 'mobx-react';
import { ipcRenderer } from 'electron';
import { useTranslation } from 'react-i18next';
import NumberFormat from 'react-number-format';
import { getRootStore } from '../../../models/root-store';

const useStyles = makeStyles({
  content: {
    alignItems: 'center',
  },
  root: {
    flexGrow: 1,
  },
  paper: {
    backgroundColor: '#95A5A6',
    textAlign: 'center',
  },
  paperInput: {
    backgroundColor: '#666666',
    alignItems: 'center',
    justifyContentItems: 'baseline',
    padding: 10,
    margin: 10,
    minHeight: 70,
  },
  paperInputNested: {
    backgroundColor: '#7d7d7d',
    alignItems: 'center',
    justifyContentItems: 'baseline',
    padding: 10,
    margin: 10,
    minHeight: 70,
  },
  button: {
    backgroundColor: '#3E3E3E',
    height: '90%',
    width: '90%',
    margin: 25,
    padding: 25,
    textAlign: 'center',
  },
  typo: {
    fontSize: 'auto',
  },
  paperTop: {
    alignItems: 'center',
    padding: 10,
    marginTop: 15,
    margin: 15,
  },
  input: {
    color: 'white',
    fontSize: '1.1em',
    padding: '5px',
    width: 'auto',
  },
  inputLabel: {
    color: 'black',
    fontSize: '20px',
  },
  inputNumbers: {
    color: 'white',
    fontSize: '1.2em',
    padding: '5px',
    width: 'auto',
  },
});

interface NumberFormatPriceProps {
  inputRef: (instance: NumberFormat | null) => void;
  onChange: (event: { target: { name: string; value: string } }) => void;
  name: string;
}

function NumberFormatPrice(props: NumberFormatPriceProps) {
  const { inputRef, onChange, ...other } = props;

  return (
    <NumberFormat
      {...other}
      getInputRef={inputRef}
      onValueChange={(values) => {
        onChange({
          target: {
            name: props.name,
            value: values.value,
          },
        });
      }}
      thousandSeparator
      fixedDecimalScale
      decimalScale={2}
      prefix="€"
    />
  );
}

const PoFAdvanced = observer(() => {
  const classes = useStyles();
  const [rootStore] = useState(() => getRootStore());
  const [selectedSerialPort, setSelectedSerialPort] = React.useState(
    rootStore.settings.getSerialByPath(rootStore.settings.serialPortPath)
  );
  const [errorLogin, setErrorLogin] = useState(false);
  const [errorNoAccount, setErrorNoAccount] = useState(false);
  const [progressZones, setProgressZones] = useState(-1); // When not loaded yet it's -1, when starting to load it's 0
  const { t } = useTranslation();

  const authenticate = async () => {
    if (typeof rootStore.acs01List.defaultAcs01 === 'undefined') {
      setErrorNoAccount(true);
      return new Error();
    }
    setErrorNoAccount(false);
    setErrorLogin(false);
    // Authenticate on the Acs01 locally
    const loginLocal = await ipcRenderer.invoke(
      'loginLocal',
      rootStore.acs01List?.defaultAcs01.localUrl
    );

    if (loginLocal?.role === 100) {
      rootStore.acs01List.setLocalStatus(1);
      if (
        typeof rootStore.passageList.defaultPassageId !== 'undefined' &&
        rootStore.passageList.defaultPassageId !== ''
      ) {
        setProgressZones(50);
        const getPassage = await ipcRenderer.invoke('passageById', [
          rootStore.acs01List?.defaultAcs01.localUrl,
          rootStore.passageList?.defaultPassageId,
        ]);
        if (getPassage) {
          rootStore.passageList.setDefault(getPassage);
          setProgressZones(100);
        } else setErrorLogin(true);
      }
      if (
        typeof rootStore.auxList.defaultLoopId !== 'undefined' &&
        typeof rootStore.auxList.defaultLoop !== 'undefined' &&
        rootStore.auxList.defaultLoopId !== ''
      ) {
        const getAux = await ipcRenderer.invoke('auxById', [
          rootStore.acs01List?.defaultAcs01.localUrl,
          rootStore.auxList?.defaultLoopId,
        ]);
        if (getAux) rootStore.auxList.setDefault(getAux);
        else setErrorLogin(true);
      }
      if (
        typeof rootStore.printerList.defaultPrinterId !== 'undefined' &&
        typeof rootStore.printerList.defaultPrinter !== 'undefined' &&
        rootStore.printerList.defaultPrinterId !== ''
      ) {
        const getPrinter = await ipcRenderer.invoke('printerById', [
          rootStore.acs01List?.defaultAcs01.localUrl,
          rootStore.printerList?.defaultPrinterId,
        ]);
        if (getPrinter) rootStore.printerList.setDefaultPrinter(getPrinter);
        else setErrorLogin(true);
      }
      if (
        typeof rootStore.scenarioList.defaultScenarioId !== 'undefined' &&
        typeof rootStore.scenarioList.defaultScenario !== 'undefined' &&
        rootStore.scenarioList.defaultScenarioConfigured
      ) {
        const getScenario = await ipcRenderer.invoke('scenarioById', [
          rootStore.acs01List?.defaultAcs01.localUrl,
          rootStore.scenarioList?.defaultScenarioId,
        ]);
        if (getScenario) rootStore.scenarioList.setDefaultScenario(getScenario);
        else setErrorLogin(true);
      }
      return 'OK';
    }
    rootStore.acs01List.setLocalStatus(0);
    setErrorLogin(true);
    return new Error();
  };

  const handleChangeLostTicket = (event: any, newValue: any) => {
    if (newValue !== null) {
      rootStore.settings.setLostTicket(newValue.id);
    }
  };

  const handleChangeSerialPort = (event: any, newValue: any) => {
    if (newValue !== null && newValue !== 'No ports detected') {
      setSelectedSerialPort(newValue.path);
      ipcRenderer.send('setSerialPath', newValue.path);
      rootStore.settings.setSerialPortPath(newValue.path);
    }
  };

  const handleRestart = (event: any) => {
    ipcRenderer.send('restart', 'tst');
  };

  return (
    <>
      {rootStore.acs01List.defaultAcs01 &&
      rootStore.acs01List.defaultAcs01?.localName !== '' ? (
        <Grid container justifyContent="center" alignItems="center" spacing={0}>
          <Grid item xs={12} md={12} lg={12} xl={12}>
            <Paper
              elevation={3}
              className={classes.paperTop}
              style={{ background: `${rootStore.settings.backgroundColor}` }}
            >
              <Paper className={classes.paperInput}>
                <Grid item xs={12}>
                  <Typography
                    className={classes.content}
                    variant="h6"
                    component="span"
                  >
                    Use scanner connected to display
                  </Typography>
                  <Switch
                    checked={rootStore.terminal.scannerConnectedToDisplay}
                    onChange={async () => {
                      rootStore.terminal.setScannerConnectedToDisplay(
                        !rootStore.terminal.scannerConnectedToDisplay
                      );
                    }}
                    inputProps={{ 'aria-label': 'controlled' }}
                  />
                </Grid>
              </Paper>
              <Paper className={classes.paperInput}>
                <Grid item xs={12}>
                  <Typography
                    className={classes.content}
                    variant="h6"
                    component="span"
                  >
                    Veto scenario
                  </Typography>
                  <Switch
                    checked={rootStore.scenarioList.defaultScenarioConfigured}
                    onChange={async () => {
                      rootStore.scenarioList.setDefaultScenarioConfigured(
                        !rootStore.scenarioList.defaultScenarioConfigured
                      );
                      rootStore.scenarioList.setDefaultScenarioId('');
                      rootStore.scenarioList.setDefaultScenario(undefined);
                      await authenticate();
                    }}
                    inputProps={{ 'aria-label': 'controlled' }}
                  />
                </Grid>
                {rootStore.scenarioList.defaultScenarioConfigured ? (
                  <Grid item xs={12}>
                    <Paper className={classes.paperInputNested}>
                      <br />
                      <Autocomplete
                        id="Mode"
                        value={rootStore.scenarioList.getScenarioById(
                          rootStore.scenarioList.defaultScenarioId
                        )}
                        options={rootStore.scenarioList.all}
                        getOptionLabel={(option) => option.name}
                        onChange={async (event: any, newValue: any) => {
                          rootStore.scenarioList.setDefaultScenarioId(
                            newValue.id
                          );
                          await authenticate();
                        }}
                        selectOnFocus
                        clearOnBlur
                        renderInput={(params) => (
                          <TextField
                            {...params}
                            label="Veto scenario"
                            variant="outlined"
                          />
                        )}
                      />
                      <br />
                    </Paper>
                  </Grid>
                ) : null}
              </Paper>
              {rootStore.settings.applicationMode === 3 ? (
                <Paper className={classes.paperInputNested}>
                  <br />
                  <TextField
                    id="filled-name"
                    label="Ip-EMV"
                    fullWidth
                    value={rootStore.settings.ipEMV}
                    onChange={(e) =>
                      rootStore.settings.setIpEMV(e.target.value)
                    }
                    variant="outlined"
                  />
                  <br />
                  <br />
                  <FormControl fullWidth variant="outlined">
                    <TextField
                      variant="outlined"
                      label={t('addTicketModelView.Price')}
                      value={rootStore.terminal.lostTicketPrice}
                      onChange={(ev) => {
                        rootStore.terminal.setLostTicketPrice(
                          ev.target.value || '0.00'
                        );
                      }}
                      InputProps={{
                        className: classes.inputNumbers,
                      }}
                      InputLabelProps={{
                        className: classes.inputLabel,
                      }}
                    />
                  </FormControl>
                  <br />
                  <br />
                  {rootStore.ticketList.all.length !== 0 ? (
                    <>
                      <Autocomplete
                        id="lostTicket"
                        value={rootStore.ticketList.getTicketById(
                          rootStore.settings.lostTicketId
                        )}
                        options={rootStore.ticketList.all}
                        getOptionLabel={(option) => option.title}
                        onChange={handleChangeLostTicket}
                        disableClearable
                        selectOnFocus
                        clearOnBlur
                        renderInput={(params) => (
                          <TextField
                            {...params}
                            label="Lost ticket"
                            variant="outlined"
                          />
                        )}
                      />
                      <br />
                      <br />
                    </>
                  ) : null}
                  {rootStore.settings.serialPortList.length === 0 ? (
                    <Typography className={classes.content} variant="body1">
                      No serial port detected.
                    </Typography>
                  ) : (
                    <>
                      <Autocomplete
                        id="serialPort"
                        value={rootStore.settings.getSerialByPath(
                          rootStore.settings.serialPortPath
                        )}
                        options={rootStore.settings.serialPortList}
                        getOptionLabel={(option) => option.path}
                        onChange={handleChangeSerialPort}
                        disableClearable
                        selectOnFocus
                        clearOnBlur
                        renderInput={(params) => (
                          <TextField
                            {...params}
                            label="Serial port"
                            variant="outlined"
                          />
                        )}
                      />
                      <br />
                    </>
                  )}
                  {selectedSerialPort !==
                  rootStore.settings.getSerialByPath(
                    rootStore.settings.serialPortPath
                  ) ? (
                    <>
                      <Typography className={classes.content} variant="body1">
                        Please reboot application in order for the changes to
                        apply.
                      </Typography>
                      <Button
                        variant="contained"
                        color="primary"
                        onClick={handleRestart}
                      >
                        Restart
                      </Button>
                    </>
                  ) : null}
                </Paper>
              ) : null}
              <Paper className={classes.paperInput}>
                <Grid item xs={12}>
                  <Typography
                    className={classes.content}
                    variant="h6"
                    component="span"
                  >
                    Allow simple tickets
                  </Typography>
                  <Switch
                    checked={rootStore.scannedTicketList.useSimpleTicket}
                    onChange={async () => {
                      rootStore.scannedTicketList.setUseSimpleTicket(
                        !rootStore.scannedTicketList.useSimpleTicket
                      );
                    }}
                    inputProps={{ 'aria-label': 'controlled' }}
                  />
                </Grid>
                {rootStore.scannedTicketList.useSimpleTicket ? (
                  <Grid item xs={12}>
                    <Paper className={classes.paperInputNested}>
                      <br />
                      <TextField
                        label="Prefix simple ticket"
                        value={rootStore.scannedTicketList.prefixSimpleTicket}
                        placeholder="Prefix simple ticket"
                        variant="outlined"
                        fullWidth
                        onChange={(ev) => {
                          rootStore.scannedTicketList.setPrefixSimpleTicket(
                            ev.target.value || ''
                          );
                        }}
                        InputProps={{
                          className: classes.input,
                        }}
                        InputLabelProps={{
                          className: classes.inputLabel,
                        }}
                      />
                      <br />
                    </Paper>
                  </Grid>
                ) : null}
              </Paper>
            </Paper>
          </Grid>
        </Grid>
      ) : null}
    </>
  );
});

export default PoFAdvanced;
