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

import Typography from '@mui/material/Typography';
import { observer } from 'mobx-react';
import { Autocomplete } from '@mui/material';
import { getRootStore } from '../../models/root-store.ts';
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',
  },
  paperTop: {
    alignItems: 'center',
    padding: 10,
    marginTop: 15,
    margin: 15,
  },
  input: {
    color: 'white',
    fontSize: '1.1em',
    padding: '5px',
    width: 'auto',
  },
});

const noneReader = { id: '', name: 'None' };

const KeypadSettings = observer(() => {
  const classes = useStyles();
  const [rootStore] = useState(() => getRootStore());
  const [errorLogin, setErrorLogin] = React.useState(false);
  const readerOptions = [noneReader, ...rootStore.readerList.all];

  const authenticate = async () => {
    if (typeof rootStore.acs01List.defaultAcs01 === 'undefined') {
      return new Error();
    }
    setErrorLogin(false);
    // Authenticate on the Acs01 locally
    try {
      const loginLocal = await ipcRenderer.invoke(
        'loginLocal',
        rootStore.acs01List?.defaultAcs01.localUrl
      );
      if (loginLocal?.role === 100) {
        rootStore.acs01List.setLocalStatus(1);
        const getReaders = await ipcRenderer.invoke('getReaders', [
          rootStore.acs01List?.defaultAcs01.localUrl,
        ]);
        if (Array.isArray(getReaders)) {
          console.log('READERS: ', getReaders);
          rootStore.readerList.setReadersFromDefaultPassage(getReaders);
        } else setErrorLogin(true);
        if (typeof rootStore.readerList.defaultReaderId !== 'undefined') {
          const getReader = await ipcRenderer.invoke('readerById', [
            rootStore.acs01List?.defaultAcs01.localUrl,
            rootStore.readerList?.defaultReaderId,
          ]);
          if (getReader) rootStore.readerList.setDefault(getReader);
          else setErrorLogin(true);
        }
      }
    } catch (error) {
      rootStore.acs01List.setLocalStatus(0);
      setErrorLogin(true);
      return console.log('error on authenticate');
    }
  };

  const runFetchCreateReader = async () => {
    if (typeof rootStore.acs01List?.defaultAcs01 === 'undefined') return;
  
    try {
      await authenticate(); // optional: keep or move after
      await ipcRenderer.invoke('createHttpReader', [
        rootStore.acs01List.defaultAcs01.localUrl,
        rootStore.acs01List.defaultAcs01.moduleId,
        rootStore.passageList.defaultPassageId,
        rootStore.passageList.defaultPassage?.zone_1.id,
      ]);
  
      // refresh reader list
      const readers = await ipcRenderer.invoke('getReaders', [
        rootStore.acs01List.defaultAcs01.localUrl,
      ]);
  
      if (Array.isArray(readers)) {
        rootStore.readerList.setReadersFromDefaultPassage(readers);
      }
    } catch (error) {
      console.log('error on create reader');
    }
  };

  useEffect(() => {
    (async () => {
      await authenticate();
    })();
    return () => {};
  }, []);

  return (
    <>
      <Grid item xs={12} md={12} lg={6}>
        <Paper className={classes.paperInput}>
          <Typography className={classes.content} variant="h6">
            Readers
          </Typography>
          <Paper className={classes.paperInputNested}>
            <Button
              variant="contained"
              color="secondary"
              onClick={() => runFetchCreateReader()}
            >
              Create reader
            </Button>
          </Paper>
        </Paper>
      </Grid>
      {rootStore.acs01List.defaultAcs01 &&
      rootStore.readerList.all &&
      rootStore.acs01List.defaultAcs01?.localName !== '' &&
      rootStore.passageList.defaultPassageId !== '' ? (
        <Grid item xs={12} md={6} lg={6}>
          <Paper className={classes.paperInput}>
            <Typography className={classes.content} variant="h6">
              Readers
            </Typography>
            <Paper className={classes.paperInputNested}>
              <br />
              <Autocomplete
                id="Mode"
                value={
                  rootStore.readerList.defaultReaderId
                    ? rootStore.readerList.getReaderById(rootStore.readerList.defaultReaderId)
                    : noneReader
                }
                options={readerOptions}
                getOptionLabel={(option) => option.name}
                onChange={async (event: any, newValue: any) => {
                  if (newValue?.id === '') {
                    rootStore.readerList.setDefaultReaderId(undefined);
                  } else {
                    rootStore.readerList.setDefaultReaderId(newValue.id);
                    await authenticate();
                  }
                }}
                disableClearable
                selectOnFocus
                clearOnBlur
                renderInput={(params) => (
                  <TextField {...params} label="Reader" 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>
        </Grid>
      ) : null}
    </>
  );
});

function KeypadConfig() {
  const classes = useStyles();
  const [rootStore] = useState(() => getRootStore());

  return (
    <Grid container justifyContent="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 item xs={12}>
            <Typography
              style={{
                color: rootStore.settings.darkMode ? 'white' : 'black',
              }}
              className={classes.content}
              variant="h4"
            >
              Configuration keypad
            </Typography>
          </Grid>
          <Grid container justifyContent="center" spacing={0}>
            <KeypadSettings />
          </Grid>
        </Paper>
      </Grid>
    </Grid>
  );
}

export default observer(KeypadConfig);
