/* 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, Card, Switch } 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 { Autocomplete } from '@mui/material';
import { getRootStore } from '../../../models/root-store';
import { ipcRenderer } from 'electron';

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,
  },
  feedback: {
    backgroundColor: '#b0b0b0',
    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',
  },
  input: {
    color: 'white',
    fontSize: '1.1em',
    padding: '5px',
    width: 'auto',
  },
});

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>
  );
}

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

  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.auxList.defaultLostTicketOutputId !== 'undefined' &&
        typeof rootStore.auxList.defaultLostTicketOutput !== 'undefined' &&
        rootStore.auxList.defaultLostTicketOutputId !== ''
      ) {
        const getAux2 = await ipcRenderer.invoke('auxById', [
          rootStore.acs01List?.defaultAcs01.localUrl,
          rootStore.auxList?.defaultLostTicketOutputId,
        ]);
        if (getAux2) rootStore.auxList.setDefaultLostTicketOutput(getAux2);
        else setErrorLogin(true);
      }
      if (
        typeof rootStore.auxList.defaultUnknownTicketOutputId !== 'undefined' &&
        typeof rootStore.auxList.defaultUnknownTicketOutput !== 'undefined' &&
        rootStore.auxList.defaultUnknownTicketOutputId !== ''
      ) {
        const getAux3 = await ipcRenderer.invoke('auxById', [
          rootStore.acs01List?.defaultAcs01.localUrl,
          rootStore.auxList?.defaultUnknownTicketOutputId,
        ]);
        if (getAux3) rootStore.auxList.setDefaultUnknownTicketOutput(getAux3);
        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();
  };

  return (
    <>
      {rootStore.acs01List.defaultAcs01 &&
      rootStore.acs01List.defaultAcs01?.localName !== '' ? (
        <Grid item xs={12} md={4} lg={4}>
          <Paper className={classes.paperInput}>
            <Typography className={classes.content} variant="h6">
              Passage
            </Typography>
            <Paper className={classes.paperInputNested}>
              <br />
              <Autocomplete
                id="Mode"
                value={rootStore.passageList.getPassageById(
                  rootStore.passageList.defaultPassage?.id
                )}
                options={rootStore.passageList.all}
                getOptionLabel={(option) => option.name}
                onChange={async (_event: any, newValue: any) => {
                  rootStore.passageList.setDefault(undefined);
                  setProgressZones(10);
                  rootStore.passageList.setDefaultPassageId(newValue.id);
                  await authenticate();
                }}
                selectOnFocus
                clearOnBlur
                disableClearable
                renderInput={(params) => (
                  <TextField {...params} label="Passage" variant="outlined" />
                )}
              />
              <br />
              {errorLogin ? (
                <Card className={classes.feedback} style={{ marginBottom: 50 }}>
                  <Typography
                    style={{ color: 'red', marginTop: 20 }}
                    variant="body1"
                  >
                    Please check the network and try again.
                  </Typography>
                </Card>
              ) : null}
            </Paper>
          </Paper>

          {rootStore.passageList.defaultPassage?.zone_1 &&
          rootStore.passageList.defaultPassage?.zone_2 &&
          progressZones >= -1 ? (
            <Paper className={classes.paperInput}>
              <Typography className={classes.content} variant="h6">
                Zone where the passage gives access to
              </Typography>
              <Paper className={classes.paperInputNested}>
                <br />
                <Autocomplete
                  id="Mode"
                  value={rootStore.passageList.zoneTo}
                  options={[0, 1]}
                  getOptionLabel={(option) => {
                    if (option === 0) {
                      return `${rootStore.passageList.defaultPassage?.zone_1.name}`;
                    }
                    return `${rootStore.passageList.defaultPassage?.zone_2.name}`;
                  }}
                  onChange={(event: any, newValue: any) => {
                    rootStore.passageList.setZoneTo(newValue);
                  }}
                  disableClearable
                  selectOnFocus
                  clearOnBlur
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      label="Passage gives access to"
                      variant="outlined"
                    />
                  )}
                />
                <br />
              </Paper>
            </Paper>
          ) : (
            <Paper className={classes.paperInput}>
              <Typography className={classes.content} variant="h6">
                Please select a passage first
              </Typography>
              {progressZones >= 0 ? (
                <Typography variant="h4">
                  <CircularProgressWithLabel value={progressZones} />
                </Typography>
              ) : null}
            </Paper>
          )}
        </Grid>
      ) : null}

      {rootStore.acs01List.defaultAcs01 &&
      rootStore.acs01List.defaultAcs01?.localName !== '' ? (
        <>
          <Grid item xs={12} md={4} lg={4}>
            <Paper className={classes.paperInput}>
              <Grid item xs={12}>
                <Typography
                  className={classes.content}
                  variant="h6"
                  component="span"
                >
                  Presence loop
                </Typography>
                <Switch
                  checked={rootStore.auxList.defaultLoopConfigured}
                  onChange={async () => {
                    rootStore.auxList.setDefaultLoopConfigured(
                      !rootStore.auxList.defaultLoopConfigured
                    );
                    rootStore.auxList.setDefaultLoopId('');
                    rootStore.auxList.setDefaultLoop(undefined);
                    await authenticate();
                  }}
                  inputProps={{ 'aria-label': 'controlled' }}
                />
              </Grid>
              {rootStore.auxList.defaultLoopConfigured ? (
                <Grid item xs={12}>
                  <Paper className={classes.paperInputNested}>
                    <br />
                    <Autocomplete
                      id="Mode"
                      value={rootStore.auxList.getAuxById(
                        rootStore.auxList.defaultLoopId
                      )}
                      options={rootStore.auxList.allInputs}
                      getOptionLabel={(option) => option.name}
                      onChange={async (event: any, newValue: any) => {
                        rootStore.auxList.setDefaultLoopId(newValue.id);
                        await authenticate();
                      }}
                      selectOnFocus
                      clearOnBlur
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label="Input loop"
                          variant="outlined"
                        />
                      )}
                    />
                    <br />
                  </Paper>
                </Grid>
              ) : null}
            </Paper>
            <Paper className={classes.paperInput}>
              <Grid item xs={12}>
                <Typography
                  className={classes.content}
                  variant="h6"
                  component="span"
                >
                  Lost ticket output
                </Typography>
                <Switch
                  checked={rootStore.auxList.defaultLostTicketOutputConfigured}
                  onChange={async () => {
                    rootStore.auxList.setDefaultLostTicketOutputConfigured(
                      !rootStore.auxList.defaultLostTicketOutputConfigured
                    );
                    rootStore.auxList.setDefaultLostTicketOutputId('');
                    rootStore.auxList.setDefaultLostTicketOutput(undefined);
                    await authenticate();
                  }}
                  inputProps={{ 'aria-label': 'controlled' }}
                />
              </Grid>
              {rootStore.auxList.defaultLostTicketOutputConfigured ? (
                <Grid item xs={12}>
                  <Paper className={classes.paperInputNested}>
                    <br />
                    <Autocomplete
                      id="Mode"
                      value={rootStore.auxList.getAuxById(
                        rootStore.auxList.defaultLostTicketOutputId
                      )}
                      options={rootStore.auxList.allOutputs}
                      getOptionLabel={(option) => option.name}
                      onChange={async (event: any, newValue: any) => {
                        rootStore.auxList.setDefaultLostTicketOutputId(
                          newValue.id
                        );
                        await authenticate();
                      }}
                      selectOnFocus
                      clearOnBlur
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label="Output lost ticket"
                          variant="outlined"
                        />
                      )}
                    />
                    <br />
                  </Paper>
                </Grid>
              ) : null}
            </Paper>
          </Grid>

          <Grid item xs={12} md={4} lg={4}>
            <Paper className={classes.paperInput}>
              <Grid item xs={12}>
                <Typography
                  className={classes.content}
                  variant="h6"
                  component="span"
                >
                  Unknown ticket output
                </Typography>
                <Switch
                  checked={
                    rootStore.auxList.defaultUnknownTicketOutputConfigured
                  }
                  onChange={async () => {
                    rootStore.auxList.setDefaultUnknownTicketOutputConfigured(
                      !rootStore.auxList.defaultUnknownTicketOutputConfigured
                    );
                    rootStore.auxList.setDefaultUnknownTicketOutputId('');
                    rootStore.auxList.setDefaultUnknownTicketOutput(undefined);
                    await authenticate();
                  }}
                  inputProps={{ 'aria-label': 'controlled' }}
                />
              </Grid>
              {rootStore.auxList.defaultUnknownTicketOutputConfigured ? (
                <Grid item xs={12}>
                  <Paper className={classes.paperInputNested}>
                    <br />
                    <Autocomplete
                      id="Mode"
                      value={rootStore.auxList.getAuxById(
                        rootStore.auxList.defaultUnknownTicketOutputId
                      )}
                      options={rootStore.auxList.allOutputs}
                      getOptionLabel={(option) => option.name}
                      onChange={async (event: any, newValue: any) => {
                        rootStore.auxList.setDefaultUnknownTicketOutputId(
                          newValue.id
                        );
                        await authenticate();
                      }}
                      selectOnFocus
                      clearOnBlur
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label="Output unknown ticket"
                          variant="outlined"
                        />
                      )}
                    />
                    <br />
                  </Paper>
                </Grid>
              ) : null}
            </Paper>
          </Grid>
        </>
      ) : null}
    </>
  );
});

export default PoF;
