/* eslint-disable @typescript-eslint/no-shadow */
/* eslint-disable react/jsx-key */
/* eslint-disable react/destructuring-assignment */
/* eslint-disable compat/compat */
/* eslint-disable react/jsx-props-no-spreading */
import React, { useEffect, useState } from 'react';
import {
  Grid,
  Paper,
  FormControlLabel,
  Checkbox,
  TextField,
  Slider,
  Button,
  FormControl,
  Fab,
  InputAdornment,
  IconButton,
  Card,
  Avatar,
  Theme,
  createStyles,
  Switch,
  Autocomplete,
} 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 AvatarGroup from '@mui/lab/AvatarGroup';
import { observer } from 'mobx-react';
import { Cookie, ipcRenderer, session } from 'electron';
import { useTranslation } from 'react-i18next';
// import { locale } from "core-js";
import VisibilityIcon from '@mui/icons-material/Visibility';
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';
import {
  DataGrid,
  GridCellParams,
  GridColDef,
  GridToolbar,
} from '@mui/x-data-grid';
import { toJS } from 'mobx';
import { clone } from 'mobx-keystone';
import { useNavigate } from 'react-router-dom';
import { getRootStore, RootStore } from '../../models/root-store.ts';
import Acs01 from '../../models/Remote/Acs01';
import EntryUnit from './TerminalConfig/EntryUnit';
import ExitUnit from './TerminalConfig/ExitUnit';
import ExitUnitPay from './TerminalConfig/ExitUnitPay';
import PoF from './TerminalConfig/PoF';
import Counter from '../../models/Remote/Counter';

const useStyles = makeStyles({
  dataGrid: {
    border: 0,
    color: 'white',
  },
  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,
  },
  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,
  },
});

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 LedPanelConfig() {
  const classes = useStyles();
  const [rootStore] = useState(() => getRootStore());
  const [errorLogin, setErrorLogin] = useState(false);
  const [progress, setProgress] = useState(0);
  const [message, setMessage] = useState(0);
  const [zeroConf, setZeroConf] = useState(false);

  const [selectedCounter, setSelectedCounter] = useState<Counter>();
  const [name, setName] = useState('');
  const [ip, setIp] = useState('');
  const [maxSize, setMaxSize] = useState(100);
  const [resetMode, setResetMode] = useState({ name: 'no reset', value: 0 });

  const [counterIds, setCounterIds] = useState<string[]>([]);
  const [operator, setOperator] = useState('End of counter group');

  const [progressDone, setProgressDone] = useState(false);
  const [progressZones, setProgressZones] = useState(-1); // When not loaded yet it's -1, when starting to load it's 0
  const history = useNavigate();
  const { t } = useTranslation();
  const runFetchLoginLocal = async () => {
    if (typeof rootStore.acs01List?.defaultAcs01 === 'undefined') {
      return new Error();
    }
    const fetchData: any = await fetch(
      `http://${rootStore.acs01List?.defaultAcs01.localUrl}/apiv1/auth/login`,
      {
        method: 'POST',
        body: JSON.stringify({
          username: rootStore.acs01List?.defaultAcs01.username,
          password: rootStore.acs01List?.defaultAcs01.password,
        }),
      }
    )
      .then((response: any) => {
        if (response.status !== 200) {
          return new Error(response.status);
        }
        return response.json();
      })
      .then((json: any) => {
        console.log('local', json);
        return json;
      })
      .catch((error) => {
        console.log('non local');
        return error;
      });
    rootStore.acs01List.setLoginStatus(rootStore.acs01List.loginStatus + 1);

    return fetchData;
  };

  const testRunFetchLoginLocal = async (url: string) => {
    if (typeof rootStore.acs01List?.defaultAcs01 === 'undefined') {
      return new Error();
    }
    const fetchData: any = await fetch(`http://${url}/apiv1/auth/login`, {
      method: 'POST',
      body: JSON.stringify({
        username: rootStore.acs01List?.defaultAcs01.username,
        password: rootStore.acs01List?.defaultAcs01.password,
      }),
    })
      .then((response: any) => {
        if (response.status !== 200) {
          return new Error(response.status);
        }
        return response.json();
      })
      .then((json: any) => {
        console.log('local', json);
        return json;
      })
      .catch((error) => {
        console.log('non local');
        return error;
      });
    return fetchData;
  };

  const runFetchGetPassageById = async () => {
    if (typeof rootStore.acs01List?.defaultAcs01 === 'undefined') {
      return new Error();
    }
    const fetchData: any = await fetch(
      `http://${rootStore.acs01List?.defaultAcs01.localUrl}/apiv1/passage/${rootStore.passageList?.defaultPassageId}`,
      {
        method: 'GET',
      }
    )
      .then((response: any) => {
        if (response.status !== 200) {
          return new Error(response.status);
        }
        return response.json();
      })
      .then((json: any) => {
        console.log('passage by id', json);
        return json;
      })
      .catch((error) => {
        console.log('passage by id');
        return error;
      });
    return fetchData;
  };

  const runFetchGetPrinterById = async () => {
    if (typeof rootStore.acs01List?.defaultAcs01 === 'undefined') {
      return new Error();
    }
    const fetchData: any = await fetch(
      `http://${rootStore.acs01List?.defaultAcs01.localUrl}/apiv1/printer/${rootStore.printerList?.defaultPrinterId}`,
      {
        method: 'GET',
      }
    )
      .then((response: any) => {
        if (response.status !== 200) {
          return new Error(response.status);
        }
        return response.json();
      })
      .then((json: any) => {
        console.log('passage by id', json);
        return json;
      })
      .catch((error) => {
        console.log('passage by id');
        return error;
      });
    return fetchData;
  };

  const runFetchGetAuxById = async () => {
    if (typeof rootStore.acs01List?.defaultAcs01 === 'undefined') {
      return new Error();
    }
    const fetchData: any = await fetch(
      `http://${rootStore.acs01List?.defaultAcs01.localUrl}/apiv1/io_connection/${rootStore.auxList?.defaultLoopId}`,
      {
        method: 'GET',
      }
    )
      .then((response: any) => {
        if (response.status !== 200) {
          return new Error(response.status);
        }
        return response.json();
      })
      .then((json: any) => {
        console.log('passage by id', json);
        return json;
      })
      .catch((error) => {
        console.log('passage by id');
        return error;
      });
    return fetchData;
  };

  const runFetchGetPassages = async () => {
    if (typeof rootStore.acs01List?.defaultAcs01 === 'undefined') {
      return new Error();
    }
    const fetchData: any = await fetch(
      `http://${rootStore.acs01List?.defaultAcs01.localUrl}/apiv1/passage/all`,
      {
        method: 'GET',
      }
    )
      .then((response: any) => {
        if (response.status !== 200) {
          return new Error(response.status);
        }
        return response.json();
      })
      .then((json: any) => {
        console.log('local', json);
        return json;
      })
      .catch((error) => {
        console.log('non local');
        return error;
      });
    return fetchData;
  };

  const runFetchGetAuxs = async () => {
    if (typeof rootStore.acs01List?.defaultAcs01 === 'undefined') {
      return new Error();
    }
    const fetchData: any = await fetch(
      `http://${rootStore.acs01List?.defaultAcs01.localUrl}/apiv1/io_connection/all`,
      {
        method: 'GET',
      }
    )
      .then((response: any) => {
        if (response.status !== 200) {
          return new Error(response.status);
        }
        return response.json();
      })
      .then((json: any) => {
        console.log('local', json);
        return json;
      })
      .catch((error) => {
        console.log('non local');
        return error;
      });
    return fetchData;
  };

  const runFetchGetPrinters = async () => {
    if (typeof rootStore.acs01List?.defaultAcs01 === 'undefined') {
      return new Error();
    }
    const fetchData: any = await fetch(
      `http://${rootStore.acs01List?.defaultAcs01.localUrl}/apiv1/printer/all`,
      {
        method: 'GET',
      }
    )
      .then((response: any) => {
        if (response.status !== 200) {
          return new Error(response.status);
        }
        return response.json();
      })
      .then((json: any) => {
        console.log('local', json);
        return json;
      })
      .catch((error) => {
        console.log('non local');
        return error;
      });
    return fetchData;
  };

  const runFetchGetModules = async () => {
    if (typeof rootStore.acs01List?.defaultAcs01 === 'undefined') {
      return new Error();
    }
    const fetchData: any = await fetch(
      `http://${rootStore.acs01List?.defaultAcs01.localUrl}/apiv1/module/all`,
      {
        method: 'GET',
      }
    )
      .then((response: any) => {
        if (response.status !== 200) {
          return new Error(response.status);
        }
        return response.json();
      })
      .then((json: any) => {
        console.log('local', json);
        return json;
      })
      .catch((error) => {
        console.log('non local');
        return error;
      });
    return fetchData;
  };

  const runFetchGetScenarios = async () => {
    if (typeof rootStore.acs01List?.defaultAcs01 === 'undefined') {
      return new Error();
    }
    const fetchData: any = await fetch(
      `http://${rootStore.acs01List?.defaultAcs01.localUrl}/apiv1/scenario/all`,
      {
        method: 'GET',
      }
    )
      .then((response: any) => {
        if (response.status !== 200) {
          return new Error(response.status);
        }
        return response.json();
      })
      .then((json: any) => {
        console.log('local', json);
        return json;
      })
      .catch((error) => {
        console.log('non local');
        return error;
      });
    return fetchData;
  };

  const runFetchGetScenarioById = async () => {
    if (typeof rootStore.acs01List?.defaultAcs01 === 'undefined') {
      return new Error();
    }
    const fetchData: any = await fetch(
      `http://${rootStore.acs01List?.defaultAcs01.localUrl}/apiv1/scenario/${rootStore.scenarioList?.defaultScenarioId}`,
      {
        method: 'GET',
      }
    )
      .then((response: any) => {
        if (response.status !== 200) {
          return new Error(response.status);
        }
        return response.json();
      })
      .then((json: any) => {
        console.log('scenario by id', json);
        return json;
      })
      .catch((error) => {
        console.log('scenario by id');
        return error;
      });
    return fetchData;
  };

  const testAuthenticate = async (url: string) => {
    const loginLocal = await testRunFetchLoginLocal(url);
    if (loginLocal?.role === 100) {
      rootStore.acs01List.setLoginStatus(rootStore.acs01List.loginStatus + 1);
      return true;
    }
    return false;
  };

  const runFetchGetCounters = async () => {
    if (typeof rootStore.acs01List?.defaultAcs01 === 'undefined') {
      return new Error();
    }
    const fetchData: any = await fetch(
      `http://${rootStore.acs01List?.defaultAcs01.localUrl}/apiv1/counter/all`,
      {
        method: 'GET',
      }
    )
      .then((response: any) => {
        if (response.status !== 200) {
          return new Error(response.status);
        }
        return response.json();
      })
      .then((json: any) => {
        console.log('remote', json);
        return json;
      })
      .catch((error) => {
        console.log('non remote');
        return error;
      });
    return fetchData;
  };

  const authenticate = async () => {
    if (typeof rootStore.acs01List.defaultAcs01 === 'undefined') {
      // setErrorNoAccount(true);
      return new Error();
    }
    // setErrorNoAccount(false);
    setErrorLogin(false);
    let currentProgress = 10;

    // Authenticate on the Acs01 locally
    const loginLocal = await runFetchLoginLocal();

    if (loginLocal?.role === 100) {
      currentProgress += 20;
      setProgress(currentProgress);
      rootStore.acs01List.setLocalStatus(1);
      const getPassages = await runFetchGetPassages();
      const getModules = await runFetchGetModules();
      const getCounters = await runFetchGetCounters();

      if (Array.isArray(getPassages)) {
        rootStore.passageList.set(getPassages);
        currentProgress += 20;
        setProgress(currentProgress);
      } else {
        setErrorLogin(true);
      }
      if (Array.isArray(getCounters)) {
        rootStore.counterList.setFromAcs(getCounters);
        currentProgress += 10;
        setProgress(currentProgress);
      } else {
        setErrorLogin(true);
      }
      if (Array.isArray(getModules)) {
        currentProgress += 40;
        setProgress(currentProgress);
        const moduleReceived: any = getModules.find(
          (x) => x.serialno === rootStore.acs01List.defaultAcs01?.localName
        );
        if (moduleReceived) {
          rootStore.acs01List.defaultAcs01?.setModuleId(
            moduleReceived.moduleid
          );
        }
      } else {
        setErrorLogin(true);
      }
      if (
        typeof rootStore.passageList.defaultPassageId !== 'undefined' &&
        rootStore.passageList.defaultPassageId !== ''
      ) {
        const getPassage = await runFetchGetPassageById();
        if (getPassage) rootStore.passageList.setDefault(getPassage);
        else {
          setErrorLogin(true);
        }
      }
      // setDoneFetching(fetchError);    // For animation circle
      return 'OK';
    }
    rootStore.acs01List.setLocalStatus(0);
    setErrorLogin(true);
    return new Error();
  };

  const handlePurgeDefaultAcs01 = () => {
    setErrorLogin(false);
    setProgress(0);
    setProgressDone(false);
    rootStore.acs01List.defaultAcs01?.setLocalName('');
    rootStore.acs01List.defaultAcs01?.setLocalUrl('');
    rootStore.passageList.setDefault(undefined);
    rootStore.passageList.setDefaultPassageId(undefined);
    rootStore.passageList.setDefaultConfigured(false);
    rootStore.acs01List.setConfigured(false);
  };

  const handleChangeAcs01 = async (event: any, newValue: any) => {
    if (newValue !== null) {
      // See if we can access the module
      const testLogin = await testAuthenticate(newValue.ip);
      if (testLogin) {
        rootStore.acs01List.defaultAcs01?.setLocalUrl(newValue.ip);
        rootStore.acs01List.defaultAcs01?.setLocalName(newValue.name);
        setProgress(0);
        setProgressDone(false);
        const getAllData = await authenticate();
        if (rootStore.acs01List.defaultAcs01LoginOk)
          rootStore.acs01List.setConfigured(true);
      }
      setErrorLogin(true);
    }
  };

  useEffect(() => {
    if (
      rootStore.acs01List.defaultAcs01?.localName !== '' &&
      rootStore.acs01List.defaultAcs01?.localName
    ) {
      (async () => {
        const loadInitialData = await authenticate();
      })();
    }
  }, []);

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

  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')}
                  {` counter panels`}
                </Typography>
              </Grid>
              <Grid item xs={12} md={6} lg={6}>
                <Paper className={classes.paperInput}>
                  <Paper className={classes.paperInputNested}>
                    <br />
                    {rootStore.acs01List.defaultAcs01 &&
                    rootStore.acs01List.defaultAcs01?.localName !== '' ? (
                      <>
                        <Typography className={classes.content} variant="h6">
                          Selected ACS01 module:
                          {` ${rootStore.acs01List.defaultAcs01?.localName}`}
                          <Button
                            variant="contained"
                            color="primary"
                            style={{
                              backgroundColor: '#f44336',
                              marginLeft: 50,
                            }}
                            onClick={handlePurgeDefaultAcs01}
                          >
                            delete
                          </Button>
                        </Typography>
                      </>
                    ) : (
                      <>
                        {errorLogin ? (
                          <Card
                            className={classes.feedback}
                            style={{ marginBottom: 50 }}
                          >
                            <Typography
                              style={{ color: 'red', marginTop: 20 }}
                              variant="body1"
                            >
                              Access denied.
                            </Typography>
                          </Card>
                        ) : null}
                        <Autocomplete
                          id="Mode"
                          options={rootStore.acs01List.acs01AutoDiscoverList}
                          getOptionLabel={(option) =>
                            `${option.name} ${option.ip}`
                          }
                          onChange={handleChangeAcs01}
                          selectOnFocus
                          clearOnBlur
                          renderInput={(params) => (
                            <TextField
                              {...params}
                              label="ACS01 module"
                              variant="outlined"
                            />
                          )}
                        />
                        <br />
                      </>
                    )}
                  </Paper>
                </Paper>
              </Grid>
            </>
            {rootStore.acs01List.defaultAcs01?.localName !== '' &&
            !progressDone ? (
              <Grid
                container
                justifyContent="center"
                alignItems="center"
                spacing={0}
              >
                <Typography variant="h4">
                  <CircularProgressWithLabel value={progress} />
                </Typography>
              </Grid>
            ) : null}
            {progressDone ? (
              <Grid container justifyContent="center" spacing={0}>
                <>
                  {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"
                            >
                              Build counter group
                            </Typography>
                            <Switch
                              checked={rootStore.counterList.configured}
                              onChange={async (e, chkd) => {
                                if (chkd === false) {
                                  rootStore.settings.setScreenSaverState(true);
                                }
                                rootStore.counterList.setConfigured(
                                  !rootStore.counterList.configured
                                );
                                await authenticate();
                              }}
                              inputProps={{ 'aria-label': 'controlled' }}
                            />
                          </Grid>
                          {rootStore.counterList.configured ? (
                            <Grid item xs={12}>
                              <Paper className={classes.paperInputNested}>
                                <TextField
                                  label="Name"
                                  value={name}
                                  placeholder="Name"
                                  variant="outlined"
                                  fullWidth
                                  onChange={(ev) => {
                                    setName(ev.target.value || '');
                                  }}
                                  InputProps={{
                                    className: classes.input,
                                  }}
                                  InputLabelProps={{
                                    className: classes.inputLabel,
                                  }}
                                />
                              </Paper>
                              <Paper className={classes.paperInputNested}>
                                <TextField
                                  label="Maximum size"
                                  value={maxSize}
                                  placeholder="Maximum size"
                                  variant="outlined"
                                  fullWidth
                                  onChange={(ev) => {
                                    setMaxSize(
                                      parseInt(ev.target.value, 10) || 100
                                    );
                                  }}
                                  InputProps={{
                                    className: classes.input,
                                  }}
                                  InputLabelProps={{
                                    className: classes.inputLabel,
                                  }}
                                />
                              </Paper>
                              <Paper className={classes.paperInputNested}>
                                <TextField
                                  label="Ip - led-panel"
                                  value={ip}
                                  placeholder="Ip"
                                  variant="outlined"
                                  fullWidth
                                  onChange={(ev) => {
                                    setIp(ev.target.value || '');
                                  }}
                                  InputProps={{
                                    className: classes.input,
                                  }}
                                  InputLabelProps={{
                                    className: classes.inputLabel,
                                  }}
                                />
                              </Paper>
                              <Paper className={classes.paperInputNested}>
                                <TextField
                                  label="Message"
                                  value={message}
                                  placeholder="0"
                                  variant="outlined"
                                  fullWidth
                                  onChange={(ev) => {
                                    setMessage(
                                      parseInt(ev.target.value, 10) || 0
                                    );
                                  }}
                                  InputProps={{
                                    className: classes.input,
                                  }}
                                  InputLabelProps={{
                                    className: classes.inputLabel,
                                  }}
                                />
                              </Paper>
                              <Paper className={classes.paperInputNested}>
                                XXX when 0
                                <Switch
                                  checked={zeroConf}
                                  onChange={() => setZeroConf(!zeroConf)}
                                  inputProps={{ 'aria-label': 'controlled' }}
                                />
                              </Paper>
                              <Paper className={classes.paperInputNested}>
                                <Autocomplete
                                  id="op"
                                  value={resetMode}
                                  options={[
                                    { name: 'no reset', value: 0 },
                                    { name: 'reset daily at 24:00', value: 1 },
                                    {
                                      name: 'reset weekly at sun 24:00',
                                      value: 2,
                                    },
                                  ]}
                                  getOptionLabel={(option) => option.name}
                                  onChange={(event: any, newValue: any) =>
                                    setResetMode(newValue)
                                  }
                                  selectOnFocus
                                  disableClearable
                                  renderInput={(params) => (
                                    <TextField
                                      {...params}
                                      label="Reset mode"
                                      variant="outlined"
                                    />
                                  )}
                                />
                                <br />
                              </Paper>

                              <Paper className={classes.paperInputNested}>
                                <Typography
                                  className={classes.content}
                                  variant="h6"
                                  component="span"
                                >
                                  ACS01 - counters
                                </Typography>
                                <br />
                                <br />
                                <Autocomplete
                                  id="Mode"
                                  value={selectedCounter}
                                  options={rootStore.counterList.all}
                                  getOptionLabel={(option) => option.name}
                                  onChange={(event: any, newValue: any) =>
                                    setSelectedCounter(newValue)
                                  }
                                  selectOnFocus
                                  clearOnBlur
                                  disableClearable
                                  renderInput={(params) => (
                                    <TextField
                                      {...params}
                                      label="Counter ACS01"
                                      variant="outlined"
                                    />
                                  )}
                                />
                                <br />
                                <Autocomplete
                                  id="op"
                                  value={operator}
                                  options={['+', '-', 'End of counter group']}
                                  getOptionLabel={(option) => option}
                                  onChange={(event: any, newValue: any) =>
                                    setOperator(newValue)
                                  }
                                  selectOnFocus
                                  disableClearable
                                  renderInput={(params) => (
                                    <TextField
                                      {...params}
                                      label="Operator"
                                      variant="outlined"
                                    />
                                  )}
                                />
                                <br />

                                <Button
                                  variant="contained"
                                  color="primary"
                                  disabled={operator === 'End of counter group'}
                                  onClick={() => {
                                    if (selectedCounter) {
                                      setCounterIds((counterIds) => [
                                        ...counterIds,
                                        selectedCounter.id,
                                        operator,
                                      ]);
                                    }
                                    setOperator('End of counter group');
                                  }}
                                >
                                  + add rule
                                </Button>
                              </Paper>
                              <Paper className={classes.paperInputNested}>
                                <Typography
                                  className={classes.content}
                                  variant="h6"
                                  component="div"
                                >
                                  Example counter group
                                </Typography>
                                <Typography
                                  className={classes.content}
                                  variant="h6"
                                  component="div"
                                >
                                  {counterIds.toString()}
                                  {selectedCounter?.id}
                                  {`, `}
                                  {operator}
                                </Typography>
                                <br />
                                <Button
                                  variant="contained"
                                  color="secondary"
                                  disabled={
                                    operator !== 'End of counter group' ||
                                    typeof selectedCounter === 'undefined'
                                  }
                                  onClick={() => {
                                    if (
                                      counterIds.length === 0 &&
                                      selectedCounter
                                    ) {
                                      const arrId = [
                                        selectedCounter.id,
                                        operator,
                                      ];
                                      rootStore.counterList.addCounterGroup(
                                        name,
                                        ip,
                                        maxSize,
                                        resetMode.value,
                                        message,
                                        zeroConf,
                                        arrId
                                      );
                                    } else if (selectedCounter) {
                                      const allIds = [
                                        ...counterIds,
                                        selectedCounter.id,
                                        operator,
                                      ];
                                      rootStore.counterList.addCounterGroup(
                                        name,
                                        ip,
                                        maxSize,
                                        resetMode.value,
                                        message,
                                        zeroConf,
                                        allIds
                                      );
                                    }

                                    setCounterIds([]);
                                    setSelectedCounter(undefined);
                                    setOperator('End of counter group');
                                  }}
                                >
                                  + add counter group
                                </Button>
                                <Button
                                  variant="contained"
                                  color="primary"
                                  style={{
                                    backgroundColor: '#f44336',
                                    marginLeft: 50,
                                  }}
                                  disabled={counterIds.length === 0}
                                  onClick={() => {
                                    setCounterIds([]);
                                    setSelectedCounter(undefined);
                                    setOperator('End of counter group');
                                  }}
                                >
                                  reset
                                </Button>
                              </Paper>
                            </Grid>
                          ) : null}
                        </Paper>
                      </Grid>
                    </>
                  ) : null}
                  <Grid item xs={12} md={4} lg={4}>
                    <Paper className={classes.paperInput}>
                      <Grid item xs={12}>
                        <Typography
                          className={classes.content}
                          variant="h6"
                          component="span"
                        >
                          Build counter group
                        </Typography>
                        {rootStore.counterList.$.counterGroups.toString()}
                        <Button
                          variant="contained"
                          color="secondary"
                          onClick={() => {
                            rootStore.counterList.removeAllCounterGroups();
                          }}
                        />
                      </Grid>
                    </Paper>
                  </Grid>
                </>
              </Grid>
            ) : null}
          </Grid>
        </Paper>
      </Grid>
    </Grid>
  );
}

export default observer(LedPanelConfig);
