/* eslint-disable react/jsx-key */
/* eslint-disable @typescript-eslint/ban-ts-comment */
/* eslint-disable react/jsx-props-no-spreading */
/* eslint-disable no-console */
/* eslint-disable radix */
import React, { useEffect, useState } from 'react';
import {
  Grid,
  Paper,
  FormControlLabel,
  Checkbox,
  TextField,
  Slider,
  Button,
  Autocomplete,
} from '@mui/material';
import { makeStyles } from '@mui/styles';

import Typography from '@mui/material/Typography';
import VideocamIcon from '@mui/icons-material/Videocam';
import { observer } from 'mobx-react';
import { ipcRenderer } from 'electron';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import DialpadIcon from '@mui/icons-material/Dialpad';
import AccountCircleIcon from '@mui/icons-material/AccountCircle';
import ListAltIcon from '@mui/icons-material/ListAlt';
import SettingsApplicationsIcon from '@mui/icons-material/SettingsApplications';
import ColorLensIcon from '@mui/icons-material/ColorLens';
import SystemUpdateAltIcon from '@mui/icons-material/SystemUpdateAlt';
import NumberFormat from 'react-number-format';
import packageJSON from '../../../../release/app/package.json';
import { getRootStore } from '../../models/root-store';

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 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,
  },
  paperUpdate: {
    backgroundColor: '#EAEAEA',
    alignItems: 'center',
    justifyContentItems: 'baseline',
    padding: 10,
    margin: 10,
    minHeight: 50,
  },
  buttons: {
    backgroundColor: '#666666',
    alignItems: 'center',
    alignSelf: 'center',
    padding: 10,
    margin: 10,
    minHeight: 70,
  },
  gridItemButton: {
    margin: 0,
    padding: 0,
    textAlign: 'center',
  },
  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,
  },
  typoAddTicket: {
    marginLeft: 25,
    marginTop: 10,
    marginBottom: 10,
  },
  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',
  },
  buttonInput: {
    backgroundColor: '#666666',
    alignItems: 'center',
    justifyContentContent: 'center',
    padding: 20,
    marginTop: 20,
    marginLeft: 10,
  },
});

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' },
  { id: 7, name: 'Counter panels' },
];

const resetType = [
  { id: 0, name: 'All counters to 0, every day at 22:00' },
  { id: 1, name: 'All counters to 0, every 1min ( for testing )' },
  {
    id: 2,
    name: 'All counters every 10min to a random number between 20 - 40.',
  },
];

function Settings() {
  const classes = useStyles();
  const [rootStore] = useState(() => getRootStore());
  const [infoUpdateAvailable, setInfoUpdateAvailable] = React.useState({
    version: '',
    releaseDate: '',
  });
  const [infoUpdateNotAvailable, setInfoUpdateNotAvailable] = React.useState({
    version: '',
    releaseDate: '',
  });
  const [messageUpdate, setMessageUpdate] = React.useState();
  const [updateCheck, setUpdateCheck] = React.useState(false);
  const [updateAvailable, setUpdateAvailable] = React.useState();
  const [selectedStartDate, setSelectedStartDate] = React.useState<
    Date | number | null
  >(rootStore.ticketList.defaultStart);
  const [selectedEndDate, setSelectedEndDate] = React.useState<
    Date | number | null
  >(rootStore.ticketList.defaultEnd);
  const [newTicketLevel, setNewTicketLevel] = React.useState(
    rootStore.settings.ticketLevelToShow
  );
  const [selectedSerialPort, setSelectedSerialPort] = React.useState(
    rootStore.settings.getSerialByPath(rootStore.settings.serialPortPath)
  );
  const history = useNavigate();

  const handleChangeResetMode = (event: any, newValue: any) => {
    if (newValue !== null) {
      console.log('schdulerConfig', newValue.id);
      rootStore.counterList.setResetMode(newValue.id);
      ipcRenderer.send('setSchedulerConfig', newValue.id);
    }
  };

  const handleStartDateChange = (e: any) => {
    setSelectedStartDate(e);
    rootStore.ticketList.setDefaultStart(e);
  };

  const handleEndDateChange = (e: any) => {
    setSelectedEndDate(e);
    rootStore.ticketList.setDefaultEnd(e);
  };

  useEffect(() => {
    ipcRenderer.on('updateAvailable', (event, result) => {
      if (result !== infoUpdateAvailable) {
        setInfoUpdateAvailable(result);
        setUpdateCheck(false);
      }
    });
    ipcRenderer.on('updateNotAvailable', (event, result) => {
      if (result !== infoUpdateNotAvailable) {
        setInfoUpdateNotAvailable(result);
        setUpdateCheck(false);
      }
    });
    ipcRenderer.on('checkingForUpdate', (event, result) => {
      setUpdateCheck(true);
      setTimeout(function () {
        setUpdateCheck(false);
      }, 5000);
    });
    ipcRenderer.on('messageUpdate', (event, result) => {
      setMessageUpdate(result);
    });

    return () => {
      ipcRenderer.removeAllListeners('updateAvailable');
      ipcRenderer.removeAllListeners('updateNotAvailable');
      ipcRenderer.removeAllListeners('checkingForUpdate');
      ipcRenderer.removeAllListeners('messageUpdate');
    };
  });

  const handleChangeApplication = (event: any, newValue: any) => {
    if (newValue !== null) {
      if (newValue !== 1 || newValue !== 2) {
        rootStore.settings.setScreenSaverState(true);
      }
      rootStore.settings.setApplicationMode(newValue.id);
    }
  };

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

  const handleChangeEntryTicket = (event: any, newValue: any) => {
    if (newValue !== null) {
      rootStore.settings.setEntryTicket(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 handleConfigureTemplates = (event: any) => {
    history('/configureTicketTemplates');
  };

  const handleConfigureTerminal = (event: any) => {
    history('/terminalConfig');
  };

  const handleConfigureCounterPanel = (event: any) => {
    history('/ledPanelConfig');
  };

  const handleConfigureKeypad = (event: any) => {
    history('/keypadConfig');
  };

  const handleConfigureAcs01 = (event: any) => {
    history('/acs01');
  };

  const handleConfigureCounters = (event: any) => {
    history('/counters');
  };

  const handleConfigureLayout = (event: any) => {
    history('/layout');
  };

  const handleConfigureApplication = (event: any) => {
    history('/applicationSettings');
  };

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

  const { t } = useTranslation();

  return (
    <Grid container justifyContent="center" spacing={0}>
      <Grid item xs={12} md={12} lg={10} xl={8}>
        <Paper
          elevation={3}
          className={classes.paperTop}
          style={{ background: `${rootStore.settings.backgroundColor}` }}
        >
          <Grid item xs={12} md={12} lg={12} xl={12}>
            <Typography
              style={{
                color: rootStore.settings.darkMode ? 'white' : 'black',
              }}
              className={classes.content}
              variant="h4"
            >
              {t('settings.title')}
            </Typography>
          </Grid>
          <Grid container justifyContent="center" spacing={0}>
            <Grid item xs={12} sm={6} md={6} lg={6} xl={6}>
              <Paper className={classes.paperInput}>
                <Typography className={classes.content} variant="h6">
                  Select application
                </Typography>
                <Paper className={classes.paperInputNested}>
                  <br />
                  <Autocomplete
                    id="Mode"
                    options={applicationType.filter(option => option.id !== 0 && option.id !== 3 && option.id !== 4 && option.id !== 6 && option.id !== 7)}
                    getOptionLabel={(option) => option.name}
                    value={applicationType.find((item) => item.id === rootStore.settings.applicationMode) || null}
                    onChange={handleChangeApplication}
                    disableClearable
                    selectOnFocus
                    clearOnBlur
                    renderInput={(params) => (
                      <TextField
                        {...params}
                        label="Application mode"
                        variant="outlined"
                      />
                    )}
                  />
                  <br />
                </Paper>
                <Typography className={classes.content} variant="h6">
                  {`${
                    applicationType[rootStore.settings.applicationMode].name
                  } `}
                  specific settings
                </Typography>
                {
                  // Exit unit
                }
                {applicationType[rootStore.settings.applicationMode].id ===
                2 ? (
                  <Paper className={classes.paperInputNested}>
                    <>
                      <br />
                      <Button
                        fullWidth
                        variant="contained"
                        color="primary"
                        onClick={handleConfigureAcs01}
                        style={{ padding: 15 }}
                      >
                        <AccountCircleIcon
                          // @ts-ignore
                          fontSize={rootStore.layout.iconSize}
                          style={{ paddingRight: 20 }}
                        />
                        Came.io account
                      </Button>
                      <br />
                      <br />
                      {rootStore.acs01List.defaultAcs01LoginOk ? (
                        <>
                          <Button
                            variant="contained"
                            color="primary"
                            onClick={handleConfigureTerminal}
                            fullWidth
                            style={{ padding: 15 }}
                          >
                            <ListAltIcon
                              // @ts-ignore
                              fontSize={rootStore.layout.iconSize}
                              style={{ paddingRight: 20 }}
                            />
                            terminal
                          </Button>
                          <br />
                          <br />
                        </>
                      ) : null}
                      {rootStore.acs01List.defaultAcs01 &&
                      rootStore.acs01List.defaultAcs01?.localName !== '' ? (
                        <>
                          <Button
                            variant="contained"
                            color="primary"
                            onClick={handleConfigureKeypad}
                            fullWidth
                            style={{ padding: 15 }}
                          >
                            <DialpadIcon
                              // @ts-ignore
                              fontSize={rootStore.layout.iconSize}
                              style={{ paddingRight: 20 }}
                            />
                            keypad
                          </Button>
                          <br />
                          <br />
                        </>
                      ) : null}
                    </>
                  </Paper>
                ) : null}

                {applicationType[rootStore.settings.applicationMode].id ===
                6 ? (
                  <Paper className={classes.paperInputNested}>
                    <Button
                      fullWidth
                      variant="contained"
                      color="primary"
                      onClick={handleConfigureAcs01}
                      style={{ padding: 15 }}
                    >
                      <AccountCircleIcon
                        // @ts-ignore
                        fontSize={rootStore.layout.iconSize}
                        style={{ paddingRight: 20 }}
                      />
                      Came.io accounts
                    </Button>
                    <br />
                    <br />
                    <Button
                      fullWidth
                      variant="contained"
                      color="primary"
                      onClick={handleConfigureCounters}
                      disabled={!rootStore.acs01List.configured}
                    >
                      Counters
                    </Button>
                    <br />
                    <br />
                    <Autocomplete
                      id="Mode"
                      value={resetType[rootStore.counterList.resetMode]}
                      options={resetType}
                      getOptionLabel={(option) => option.name}
                      onChange={handleChangeResetMode}
                      disableClearable
                      selectOnFocus
                      clearOnBlur
                      fullWidth
                      disabled={!rootStore.acs01List.configured}
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label="Reset mode"
                          variant="outlined"
                        />
                      )}
                    />
                  </Paper>
                ) : null}

                {applicationType[rootStore.settings.applicationMode].id ===
                7 ? (
                  <Paper className={classes.paperInputNested}>
                    <>
                      <br />
                      <Button
                        fullWidth
                        variant="contained"
                        color="primary"
                        onClick={handleConfigureAcs01}
                        style={{ padding: 15 }}
                      >
                        <AccountCircleIcon
                          // @ts-ignore
                          fontSize={rootStore.layout.iconSize}
                          style={{ paddingRight: 20 }}
                        />
                        Came.io account
                      </Button>
                      <br />
                      <br />
                      {rootStore.acs01List.defaultAcs01LoginOk ? (
                        <>
                          <Button
                            variant="contained"
                            color="primary"
                            onClick={handleConfigureCounterPanel}
                            fullWidth
                            style={{ padding: 15 }}
                          >
                            <ListAltIcon
                              // @ts-ignore
                              fontSize={rootStore.layout.iconSize}
                              style={{ paddingRight: 20 }}
                            />
                            Counter panels
                          </Button>
                          <br />
                          <br />
                        </>
                      ) : null}
                    </>
                  </Paper>
                ) : null}

                {applicationType[rootStore.settings.applicationMode].id ===
                3 ? (
                  <Paper className={classes.paperInputNested}>
                    <>
                      <br />
                      <Button
                        fullWidth
                        variant="contained"
                        color="primary"
                        onClick={handleConfigureAcs01}
                        style={{ padding: 15 }}
                      >
                        <AccountCircleIcon
                          // @ts-ignore
                          fontSize={rootStore.layout.iconSize}
                          style={{ paddingRight: 20 }}
                        />
                        Came.io account
                      </Button>
                      <br />
                      <br />
                      {rootStore.acs01List.defaultAcs01LoginOk ? (
                        <>
                          <Button
                            variant="contained"
                            color="primary"
                            onClick={handleConfigureTerminal}
                            fullWidth
                            style={{ padding: 15 }}
                          >
                            <ListAltIcon
                              // @ts-ignore
                              fontSize={rootStore.layout.iconSize}
                              style={{ paddingRight: 20 }}
                            />
                            terminal
                          </Button>
                          <br />
                          <br />
                        </>
                      ) : null}
                      {rootStore.acs01List.defaultAcs01 &&
                      rootStore.acs01List.defaultAcs01?.localName !== '' ? (
                        <>
                          <Button
                            variant="contained"
                            color="primary"
                            onClick={handleConfigureKeypad}
                            fullWidth
                            style={{ padding: 15 }}
                          >
                            <DialpadIcon
                              // @ts-ignore
                              fontSize={rootStore.layout.iconSize}
                              style={{ paddingRight: 20 }}
                            />
                            keypad
                          </Button>
                          <br />
                          <br />
                        </>
                      ) : null}
                    </>
                  </Paper>
                ) : null}

                {applicationType[rootStore.settings.applicationMode].id ===
                1 ? (
                  <Paper className={classes.paperInputNested}>
                    <>
                      <br />
                      <Button
                        fullWidth
                        variant="contained"
                        color="primary"
                        onClick={handleConfigureAcs01}
                        style={{ padding: 15 }}
                      >
                        <AccountCircleIcon
                          fontSize={rootStore.layout.iconSize}
                          style={{ paddingRight: 20 }}
                        />
                        Came.io account
                      </Button>
                      <br />
                      <br />
                      {rootStore.acs01List.defaultAcs01LoginOk ? (
                        <>
                          <Button
                            variant="contained"
                            color="primary"
                            onClick={handleConfigureTerminal}
                            fullWidth
                            style={{ padding: 15 }}
                          >
                            <ListAltIcon
                              fontSize={rootStore.layout.iconSize}
                              style={{ paddingRight: 20 }}
                            />
                            terminal
                          </Button>
                          <br />
                          <br />
                        </>
                      ) : null}
                      {rootStore.acs01List.defaultAcs01 &&
                      rootStore.acs01List.defaultAcs01?.localName !== '' ? (
                        <>
                          <Button
                            variant="contained"
                            color="primary"
                            onClick={handleConfigureKeypad}
                            fullWidth
                            style={{ padding: 15 }}
                          >
                            <DialpadIcon
                              // @ts-ignore
                              fontSize={rootStore.layout.iconSize}
                              style={{ paddingRight: 20 }}
                            />
                            keypad
                          </Button>
                          <br />
                          <br />
                        </>
                      ) : null}
                    </>
                  </Paper>
                ) : null}

                {applicationType[rootStore.settings.applicationMode].id ===
                5 ? (
                  <Paper className={classes.paperInputNested}>
                    <>
                      <br />
                      <Button
                        fullWidth
                        variant="contained"
                        color="primary"
                        onClick={handleConfigureAcs01}
                        style={{ padding: 15 }}
                      >
                        <AccountCircleIcon
                          // @ts-ignore
                          fontSize={rootStore.layout.iconSize}
                          style={{ paddingRight: 20 }}
                        />
                        Came.io account
                      </Button>
                      <br />
                      <br />
                      {rootStore.acs01List.defaultAcs01LoginOk ? (
                        <>
                          <Button
                            variant="contained"
                            color="primary"
                            onClick={handleConfigureTerminal}
                            fullWidth
                            style={{ padding: 15 }}
                          >
                            <ListAltIcon
                              // @ts-ignore
                              fontSize={rootStore.layout.iconSize}
                              style={{ paddingRight: 20 }}
                            />
                            terminal
                          </Button>
                          <br />
                          <br />
                        </>
                      ) : null}
                      {rootStore.acs01List.defaultAcs01 &&
                      rootStore.acs01List.defaultAcs01?.localName !== '' ? (
                        <>
                          <Button
                            variant="contained"
                            color="primary"
                            onClick={handleConfigureKeypad}
                            fullWidth
                            style={{ padding: 15 }}
                          >
                            <DialpadIcon
                              // @ts-ignore
                              fontSize={rootStore.layout.iconSize}
                              style={{ paddingRight: 20 }}
                            />
                            keypad
                          </Button>
                          <br />
                          <br />
                        </>
                      ) : null}
                    </>
                  </Paper>
                ) : null}

                {applicationType[rootStore.settings.applicationMode].id ===
                0 ? (
                  <>
                    <Paper className={classes.paperInputNested}>
                      <FormControlLabel
                        control={
                          <Checkbox
                            onClick={() =>
                              rootStore.settings.setPrintWithoutBasket(
                                !rootStore.settings.printWithoutBasket
                              )
                            }
                            color="primary"
                            checked={rootStore.settings.printWithoutBasket}
                          />
                        }
                        label={t('settings.Print without basket')}
                        labelPlacement="end"
                      />
                      <br />
                      <FormControlLabel
                        control={
                          <Checkbox
                            onClick={() => {
                              rootStore.settings.setSilentPrint(
                                !rootStore.settings.silentPrint
                              );
                              ipcRenderer.send(
                                'silentPrint',
                                rootStore.settings.silentPrint
                              );
                            }}
                            color="primary"
                            checked={rootStore.settings.silentPrint}
                          />
                        }
                        label={t('settings.Print without printer window')}
                        labelPlacement="end"
                      />
                      <br />
                      <br />
                      <TextField
                        label={t('settings.Ticket level to show')}
                        style={{ width: '100%' }}
                        variant="outlined"
                        value={rootStore.settings.ticketLevelToShow}
                        placeholder={t('common.level')}
                        onChange={(ev) => {
                          rootStore.settings.setTicketLevelToShow(
                            parseInt(ev.target.value) || 0
                          );
                        }}
                      />
                      <br />
                    </Paper>
                  </>
                ) : null}
              </Paper>
            </Grid>
            <Grid item xs={12} sm={6} md={6} lg={6} xl={6}>
              <Paper className={classes.paperInput}>
                <Typography className={classes.content} variant="h6">
                  General settings
                </Typography>
                <Paper className={classes.paperInputNested}>
                  <br />
                  <Button
                    variant="contained"
                    color="primary"
                    onClick={handleConfigureLayout}
                    fullWidth
                    style={{ padding: 15 }}
                  >
                    <ColorLensIcon
                      // @ts-ignore
                      fontSize={rootStore.layout.iconSize}
                      style={{ paddingRight: 20 }}
                    />
                    {t('settings.Interface')}
                  </Button>
                  <br />
                  <br />
                  <Button
                    variant="contained"
                    color="primary"
                    onClick={handleConfigureApplication}
                    fullWidth
                    style={{ padding: 15 }}
                  >
                    <SettingsApplicationsIcon
                      // @ts-ignore
                      fontSize={rootStore.layout.iconSize}
                      style={{ paddingRight: 20 }}
                    />
                    Application behaviour
                  </Button>
                  <br />
                  <br />
                </Paper>
              </Paper>
              <Paper className={classes.paperInput}>
                <Typography className={classes.content} variant="h6">
                  {t('settings.Application version')}
                </Typography>
                <Paper className={classes.paperInputNested}>
                  {/*
                  <br />
                  <Button
                    variant="contained"
                    onClick={() => ipcRenderer.send('autoUpdate', true)}
                    style={{ padding: 15 }}
                    fullWidth
                  >
                    <SystemUpdateAltIcon
                      // @ts-ignore
                      fontSize={rootStore.layout.iconSize}
                      style={{ paddingRight: 20 }}
                    />
                    Check for update
                  </Button>
                  <br />
                    */}
                    
                  <br />
                  <Typography className={classes.content} variant="body1">
                    {t('settings.Current version')}: v{packageJSON.version}
                  </Typography>
                  <Typography
                    className={classes.content}
                    style={{ color: '#004D00' }}
                    variant="body1"
                  >
                    {infoUpdateAvailable.version !== ''
                      ? `New version available: v${infoUpdateAvailable.version}`
                      : null}
                    {infoUpdateNotAvailable.version !== ''
                      ? `Current version is last version`
                      : null}
                  </Typography>
                  <Typography className={classes.content} variant="body2">
                    {messageUpdate ? (
                      <Paper
                        className={classes.paperUpdate}
                        style={{ color: '#359A45' }}
                      >
                        {messageUpdate}
                      </Paper>
                    ) : null}
                  </Typography>
                  <br />
                </Paper>
              </Paper>
            </Grid>
          </Grid>
        </Paper>
      </Grid>
    </Grid>
  );
}

export default observer(Settings);
