/* eslint-disable react/jsx-key */
/* eslint-disable react/destructuring-assignment */
/* eslint-disable compat/compat */
/* eslint-disable react/jsx-props-no-spreading */
import { useEffect, useState } from 'react';
import { Grid, Paper, Button } from '@mui/material';
import { makeStyles } from '@mui/styles';

import Box from '@mui/material/Box';
import CircularProgress from '@mui/material/CircularProgress';
import Typography from '@mui/material/Typography';
import { observer } from 'mobx-react';
import { ipcRenderer } from 'electron';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { getRootStore } from '../../../models/root-store';
import EntryUnit from './EntryUnit';
import ExitUnit from './ExitUnit';
import ExitUnitPay from './ExitUnitPay';
import PoF from './PoF';

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,
  },
  typo: {
    fontSize: 'auto',
  },
  paperTop: {
    alignItems: 'center',
    padding: 10,
    marginTop: 15,
    margin: 15,
  },
});

function CircularProgressWithLabel(props: any) {
  return (
    <Box position="relative" display="inline-flex">
      <CircularProgress variant="determinate" {...props} />
      <Box
        color="primary"
        top={0}
        left={0}
        bottom={0}
        right={0}
        position="absolute"
        display="flex"
        alignItems="center"
        justifyContent="center"
      >
        <Typography variant="caption" component="div">
          {`${Math.round(props.value)}%`}
        </Typography>
      </Box>
    </Box>
  );
}

function TerminalConfig() {
  const classes = useStyles();
  const [rootStore] = useState(() => getRootStore());
  const [progress, setProgress] = useState(0);
  const [progressDone, setProgressDone] = useState(false);
  const history = useNavigate();
  const { t } = useTranslation();

  const authenticate = async () => {
    // If no URL, we can't authenticate.
    const localUrl = rootStore.acs01List?.defaultAcs01?.localUrl;
    if (!localUrl) {
      rootStore.acs01List.setLocalStatus(0);
      return new Error('No ACS01 localUrl configured');
    }

    let currentProgress = 10;
    setProgress(currentProgress);

    // Authenticate on the Acs01 locally
    const loginLocal = await ipcRenderer.invoke('loginLocal', localUrl);

    if (loginLocal?.role === 100) {
      currentProgress += 20;
      setProgress(currentProgress);
      rootStore.acs01List.setLocalStatus(1);

      const getPassages = await ipcRenderer.invoke('passages', localUrl);
      const getAuxs = await ipcRenderer.invoke('auxs', localUrl);
      const getPrinters = await ipcRenderer.invoke('printers', localUrl);
      const getModules = await ipcRenderer.invoke('modules', localUrl);
      const getScenarios = await ipcRenderer.invoke('scenarios', localUrl);

      if (Array.isArray(getPassages)) {
        rootStore.passageList.set(getPassages);
        currentProgress += 20;
        setProgress(currentProgress);
      }
      if (Array.isArray(getAuxs)) {
        rootStore.auxList.set(getAuxs);
        currentProgress += 20;
        setProgress(currentProgress);
      }
      if (Array.isArray(getPrinters)) {
        rootStore.printerList.set(getPrinters);
        currentProgress += 10;
        setProgress(currentProgress);
      }
      if (Array.isArray(getModules)) {
        currentProgress += 10;
        setProgress(currentProgress);
        const moduleReceived: any = getModules.find(
          (x) => x.serialno === rootStore.acs01List.defaultAcs01?.localName
        );
        if (moduleReceived) {
          rootStore.acs01List.defaultAcs01?.setModuleId(moduleReceived.moduleid);
        }
      }
      if (Array.isArray(getScenarios)) {
        rootStore.scenarioList.set(getScenarios);
        currentProgress += 10;
        setProgress(currentProgress);
      }

      if (
        typeof rootStore.passageList.defaultPassageId !== 'undefined' &&
        rootStore.passageList.defaultPassageId !== ''
      ) {
        const getPassage = await ipcRenderer.invoke('passageById', [
          localUrl,
          rootStore.passageList?.defaultPassageId,
        ]);
        if (getPassage) rootStore.passageList.setDefault(getPassage);
      }

      if (
        typeof rootStore.auxList.defaultLoopId !== 'undefined' &&
        typeof rootStore.auxList.defaultLoop !== 'undefined' &&
        rootStore.auxList.defaultLoopId !== ''
      ) {
        const getAux = await ipcRenderer.invoke('auxById', [
          localUrl,
          rootStore.auxList?.defaultLoopId,
        ]);
        if (getAux) rootStore.auxList.setDefault(getAux);
      }

      if (
        typeof rootStore.printerList.defaultPrinterId !== 'undefined' &&
        typeof rootStore.printerList.defaultPrinter !== 'undefined' &&
        rootStore.printerList.defaultPrinterId !== ''
      ) {
        const getPrinter = await ipcRenderer.invoke('printerById', [
          localUrl,
          rootStore.printerList?.defaultPrinterId,
        ]);
        if (getPrinter) rootStore.printerList.setDefaultPrinter(getPrinter);
      }

      if (
        typeof rootStore.scenarioList.defaultScenarioId !== 'undefined' &&
        typeof rootStore.scenarioList.defaultScenario !== 'undefined' &&
        rootStore.scenarioList.defaultScenarioConfigured
      ) {
        const getScenario = await ipcRenderer.invoke('scenarioById', [
          localUrl,
          rootStore.scenarioList?.defaultScenarioId,
        ]);
        if (getScenario) rootStore.scenarioList.setDefaultScenario(getScenario);
      }

      // Mark as configured (since we successfully authenticated & fetched)
      rootStore.acs01List.setConfigured(true);

      return 'OK';
    }

    rootStore.acs01List.setLocalStatus(0);
    return new Error('Access denied');
  };

  // Auto-authenticate if we already have an ACS01 URL (from login page / persisted store)
  useEffect(() => {
    const localUrl = rootStore.acs01List?.defaultAcs01?.localUrl;
    if (localUrl) {
      (async () => {
        await authenticate();
      })();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (progress === 100) {
      setTimeout(() => {
        setProgressDone(true);
      }, 1000);
    }
  }, [progress]);

  const connectedUrl = rootStore.acs01List?.defaultAcs01?.localUrl;

  return (
    <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}` }}
        >
          <Grid container>
            <>
              <Grid item xs={12} md={6} lg={6}>
                <Typography
                  style={{
                    color: rootStore.settings.darkMode ? 'white' : 'black',
                  }}
                  className={classes.content}
                  variant="h4"
                >
                  {t('settings.title')}
                  {rootStore.settings.applicationMode === 1 ? ' entry terminal' : null}
                  {rootStore.settings.applicationMode === 2 ? ' exit terminal' : null}
                  {rootStore.settings.applicationMode === 5 ? ' pay in lane, exit' : null}
                  {rootStore.settings.applicationMode === 3 ? ' pay on foot' : null}
                </Typography>

                {rootStore.settings.applicationMode === 1 ? (
                  <Button
                    variant="contained"
                    color="primary"
                    style={{ margin: 10 }}
                    onClick={() => history('/entryUnitAdvanced')}
                  >
                    Advanced
                  </Button>
                ) : null}

                {rootStore.settings.applicationMode === 2 ? (
                  <Button
                    variant="contained"
                    color="primary"
                    style={{ margin: 10 }}
                    onClick={() => history('/exitUnitAdvanced')}
                  >
                    Advanced
                  </Button>
                ) : null}

                {rootStore.settings.applicationMode === 5 ? (
                  <Button
                    variant="contained"
                    color="primary"
                    style={{ margin: 10 }}
                    onClick={() => history('/exitUnitPayAdvanced')}
                  >
                    Advanced
                  </Button>
                ) : null}

                {rootStore.settings.applicationMode === 3 ? (
                  <Button
                    variant="contained"
                    color="primary"
                    style={{ margin: 10 }}
                    onClick={() => history('/pofAdvanced')}
                  >
                    Advanced
                  </Button>
                ) : null}
              </Grid>

              <Grid item xs={12} md={6} lg={6}>
                <Paper className={classes.paperInput}>
                  <Paper className={classes.paperInputNested}>
                    <br />
                    <Typography className={classes.content} variant="h6">
                      ACS01 connected to:
                      {connectedUrl ? ` ${connectedUrl}` : ' Not connected'}
                    </Typography>

                    {!connectedUrl ? (
                      <Typography
                        style={{ marginTop: 10, opacity: 0.85 }}
                        className={classes.content}
                        variant="body2"
                      >
                        Configure the ACS01 IP on the login/config page. This page is read-only.
                      </Typography>
                    ) : null}

                    <br />
                  </Paper>
                </Paper>
              </Grid>
            </>

            {connectedUrl && !progressDone ? (
              <Grid container justifyContent="center" alignItems="center" spacing={0}>
                <Typography variant="h4">
                  <CircularProgressWithLabel value={progress} />
                </Typography>
              </Grid>
            ) : null}

            {connectedUrl && progressDone ? (
              <Grid container justifyContent="center" spacing={0}>
                {rootStore.settings.applicationMode === 1 ? <EntryUnit /> : null}
                {rootStore.settings.applicationMode === 2 ? <ExitUnit /> : null}
                {rootStore.settings.applicationMode === 3 ? <PoF /> : null}
                {rootStore.settings.applicationMode === 5 ? <ExitUnitPay /> : null}
              </Grid>
            ) : null}
          </Grid>
        </Paper>
      </Grid>
    </Grid>
  );
}

export default observer(TerminalConfig);
