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

import { observer } from 'mobx-react';
import { useNavigate } from 'react-router-dom';
import PublishIcon from '@mui/icons-material/Publish';
import GetAppIcon from '@mui/icons-material/GetApp';

import BuildIcon from '@mui/icons-material/Build';
import { applySnapshot, clone, fromSnapshot, getSnapshot } from 'mobx-keystone';
import { ipcRenderer } from 'electron';
import { Autocomplete } from '@mui/material';
import { getRootStore, RootStore } from '../../../models/root-store.ts';

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 ToolsRootStore = () => {
  const classes = useStyles();
  const history = useNavigate();
  const [rootStore] = useState(() => getRootStore());

  useEffect(() => {
    ipcRenderer.on('restore-backup-payload', (event, args) => {
      if (!args) return;
      const store = applySnapshot(getRootStore(), args);
      // rootStore.acs01List.addAcs01List(args);
    });
    ipcRenderer.on('API-setBackup', (event, args) => {
      if (!args) return;
      console.log(args);
      applySnapshot(getRootStore(), args);
    });
    return () => {
      ipcRenderer.removeAllListeners('restore-backup-payload');
      ipcRenderer.removeAllListeners('API-setBackup');
    };
  }, []);

  const handleChangeApp = async (event: any, newValue: any) => {
    if (newValue !== null) {
      rootStore.acs01List.setDefaultApp(clone(newValue));
    }
  };

  const handlePurgeDefaultApp = () => {
    rootStore.acs01List.setDefaultApp(undefined);
  };

  const sendData = async () => {
    if (typeof rootStore.acs01List?.defaultApp === 'undefined') {
      return new Error();
    }

    const fetchData: any = await fetch(
      `http://${rootStore.acs01List.defaultApp.ip}:3000/setbackup`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: JSON.stringify(getSnapshot(rootStore)),
      }
    )
      .then((response: any) => {
        if (response.status !== 200) {
          return new Error(response.status);
        }
        return response.json();
      })
      .then((json: any) => {
        console.log(json);
        return json;
      })
      .catch((error) => {
        console.log(error);
        return error;
      });
    return fetchData;
  };

  const getData = async () => {
    if (typeof rootStore.acs01List?.defaultApp === 'undefined') {
      return new Error();
    }
    console.log('getData called');

    const fetchData: any = await fetch(
      `http://${rootStore.acs01List.defaultApp.ip}:3000/getbackup`,
      {
        method: 'GET',
      }
    )
      .then((response: any) => {
        if (response.status !== 200) {
          return new Error(response.status);
        }
        return response.json();
      })
      .then((json: any) => {
        console.log(json);
        return json;
      })
      .catch((error) => {
        console.log(error);
        return error;
      });
    console.log('fetchData', fetchData);
    return fetchData;
  };

  const handleSendDataApp = async () => {
    await sendData();
  };

  const handleGetDataApp = async () => {
    console.log('handleGetDataApp ');
    const remoteData = await getData();
    console.log('remotedata ', remoteData);
    const tempRootstore: RootStore = JSON.parse(remoteData);
    tempRootstore.acs01List.defaultApp = rootStore.acs01List.defaultApp;
    const store = applySnapshot(getRootStore(), tempRootstore);
  };

  return (
    <Grid container justifyContent="center" spacing={0}>
      <Grid item xs={12} md={12} lg={10} xl={8}>
        <Paper className={classes.paperInputNested}>
          <br />
          {rootStore.acs01List.defaultApp ? (
            <>
              <Grid item xs={12} md={12} lg={10} xl={8}>
                <Typography className={classes.content} variant="h6">
                  Selected CAME application:
                  {` ${rootStore.acs01List.defaultApp?.name}`}
                  <Button
                    variant="contained"
                    color="primary"
                    style={{
                      backgroundColor: '#f44336',
                      marginLeft: 50,
                    }}
                    onClick={handlePurgeDefaultApp}
                  >
                    delete
                  </Button>
                </Typography>
                <br />
                <br />
              </Grid>
              <Grid container style={{ marginLeft: -50 }} spacing={0}>
                <Grid item xs={12} md={12} lg={10} xl={8}>
                  <Button
                    variant="contained"
                    color="primary"
                    style={{
                      marginLeft: 50,
                    }}
                    onClick={handleGetDataApp}
                  >
                    <GetAppIcon
                      fontSize={rootStore.layout.iconSize}
                      style={{ paddingRight: 10 }}
                    />
                    get the data
                  </Button>
                  <Button
                    variant="contained"
                    color="primary"
                    style={{
                      marginLeft: 50,
                    }}
                    onClick={handleSendDataApp}
                  >
                    <PublishIcon
                      fontSize={rootStore.layout.iconSize}
                      style={{ paddingRight: 10 }}
                    />
                    send the data
                  </Button>
                </Grid>
              </Grid>
            </>
          ) : (
            <>
              <Autocomplete
                id="Mode"
                options={rootStore.acs01List.appAutoDiscoverList}
                getOptionLabel={(option) =>
                  `Application: ${option.name}  IP-address: ${option.ip}`
                }
                onChange={handleChangeApp}
                selectOnFocus
                clearOnBlur
                renderInput={(params) => (
                  <TextField {...params} label="Apps" variant="outlined" />
                )}
              />
              <br />
            </>
          )}
        </Paper>
      </Grid>
      <Grid item xs={12} md={12} lg={10} xl={8}>
        <Paper className={classes.paperInput}>
          <Button
            variant="contained"
            color="primary"
            onClick={() => {
              ipcRenderer.send(
                'save-backup',
                JSON.stringify(getSnapshot(rootStore))
              );
            }}
            style={{ padding: 25, marginBottom: 20 }}
            fullWidth
          >
            <BuildIcon
              fontSize={rootStore.layout.iconSize}
              style={{ paddingRight: 20 }}
            />
            Create backup
          </Button>
          <Button
            variant="contained"
            color="primary"
            onClick={() => {
              ipcRenderer.send('restore-backup');
            }}
            style={{ padding: 25 }}
            fullWidth
          >
            <BuildIcon
              fontSize={rootStore.layout.iconSize}
              style={{ paddingRight: 20 }}
            />
            Restore backup
          </Button>
        </Paper>
      </Grid>
    </Grid>
  );
};

export default observer(ToolsRootStore);
