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

import Typography from '@mui/material/Typography';
import { observer } from 'mobx-react';
import { ipcRenderer } from 'electron';
import { useTranslation } from 'react-i18next';

import { DataGrid, GridColDef } from '@mui/x-data-grid';
import { getRootStore } from '../../models/root-store';
import Acs01 from '../../models/Remote/Acs01';

type LoginIpcResult =
  | { ok: true; role: number }
  | { ok: false; error: string };

const useStyles = makeStyles({
  dataGrid: {
    border: 0,
    color: 'white',
  },
  content: {
    alignItems: 'center',
  },
  root: {
    maxWidth: 800,
  },
  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 Acs01Config() {
  const classes = useStyles();
  const [rootStore] = useState(() => getRootStore());
  const { t } = useTranslation();

  // UI state
  const [acsIp, setAcsIp] = React.useState('192.168.201.10');
  const [username, setUsername] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [isDirty, setIsDirty] = React.useState(false);

  const [errorLogin, setErrorLogin] = React.useState(false);
  const [loginSuccess, setLoginSuccess] = React.useState<boolean | undefined>();
  const [localRole, setLocalRole] = React.useState<number | undefined>(undefined);

  const [isConnected, setIsConnected] = React.useState(false);
  const [selectedRows, setSelectedRows] = useState<any>([]);

  /**
   * Restore UI from store.
   * IMPORTANT: TerminalConfig reads defaultAcs01.localUrl, so restore from localUrl first.
   */
  useEffect(() => {
    const saved: any = rootStore.acs01List?.defaultAcs01;

    if (saved) {
      const savedIp = (saved.localUrl || saved.ip || '').toString();
      if (savedIp) setAcsIp(savedIp);

      if (saved.username) setUsername(String(saved.username));
      if (typeof saved.role === 'number') setLocalRole(saved.role);

      // Never show password in UI
      setPassword('');

      const wasConnected = !!rootStore.acs01List?.defaultAcs01LoginOk;
      setIsConnected(wasConnected);
      setLoginSuccess(wasConnected ? true : undefined);
      setErrorLogin(false);
      setIsDirty(false);
    }
  }, [rootStore]);

  const runLoginLocalViaIpc = async (): Promise<LoginIpcResult> => {
    return ipcRenderer.invoke('acs01-login', {
      ip: acsIp,
      username,
      password,
    });
  };

  const addAcs01 = (role: number) => {
    rootStore.acs01List.setRemoteStatus(1);

    const ip = acsIp.trim();

    // ✅ KEY FIX: also set localUrl (used by TerminalConfig)
    const payload: any = {
      username,
      password,     // stored, but NEVER shown in UI
      ip,           // keep for grid/backwards compatibility
      localUrl: ip, // <-- TerminalConfig reads this
      localName: 'set', // optional, but matches older checks
      role,
    };

    if (
      rootStore.settings.applicationMode === 1 ||
      rootStore.settings.applicationMode === 2 ||
      rootStore.settings.applicationMode === 5 ||
      rootStore.settings.applicationMode === 7
    ) {
      rootStore.acs01List.setDefaultAcs01LoginOk(true);
      rootStore.acs01List.setDefaultAcs01(new Acs01(payload));
    } else {
      rootStore.acs01List.setDefaultAcs01(0);
      rootStore.acs01List.add(new Acs01(payload));
    }
  };

  const authenticate = async () => {
    setErrorLogin(false);
    setLoginSuccess(undefined);
    setIsDirty(false);
    setLocalRole(undefined);

    const result = await runLoginLocalViaIpc();

    if (result.ok) {
      setLocalRole(result.role);
      setLoginSuccess(true);

      addAcs01(result.role);

      setIsConnected(true);
      rootStore.acs01List.setDefaultAcs01LoginOk(true);

      // Clear local password
      setPassword('');
    } else {
      console.log('ACS01 login failed:', result.error);
      setErrorLogin(true);
      setLoginSuccess(false);
      setIsConnected(false);
      rootStore.acs01List.setDefaultAcs01LoginOk(false);

      setPassword('');
    }
  };

  const handleLogout = () => {
    rootStore.acs01List.setRemoteStatus(0);
    rootStore.acs01List.setDefaultAcs01LoginOk(false);

    setIsConnected(false);
    setLoginSuccess(undefined);
    setErrorLogin(false);
    setLocalRole(undefined);
    setIsDirty(false);

    setPassword('');
  };

  const handlePurge = () => {
    rootStore.acs01List.removeByIds(selectedRows);
    setSelectedRows([]);
  };

  const handleSelectionChange = (selection: any) => {
    setSelectedRows(selection);
  };

  const columns: GridColDef[] = [
    { field: 'ip', headerName: 'IP', width: 160 },
    { field: 'username', headerName: t('common.Name'), width: 200 },
    { field: 'role', headerName: 'Role', width: 120 },
  ];

  return (
    <div className={classes.content} data-tid="container">
      <Grid container justifyContent="center" spacing={0}>
        <Grid item xs={12} md={rootStore.settings.applicationMode === 6 ? 4 : 12}>
          <Grid container justifyContent="center" spacing={0}>
            <Grid item xs={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"
                  >
                    ACS01 {t('settings.title')}
                  </Typography>
                </Grid>

                <Paper className={classes.paperInput}>
                  <Grid container spacing={0}>
                    <Grid item xs={12} style={{ width: '100%' }}>
                      <Typography className={classes.content} variant="h6">
                        ACS01 local account
                      </Typography>

                      {errorLogin && !isConnected ? (
                        <Card className={classes.feedback}>
                          <Typography style={{ color: 'red', marginTop: 20 }} variant="body1">
                            Access denied.
                          </Typography>
                        </Card>
                      ) : null}

                      {isConnected ? (
                        <Card className={classes.feedback}>
                          <Typography style={{ color: 'green', marginTop: 20 }} variant="body1">
                            Connected to {acsIp.trim()} as {username}
                            {typeof localRole === 'number' ? ` (role: ${localRole})` : ''}.
                          </Typography>
                        </Card>
                      ) : null}

                      <Paper className={classes.paperInput}>
                        <FormControl fullWidth variant="outlined">
                          <TextField
                            variant="outlined"
                            label="ACS01 IP address"
                            value={acsIp}
                            placeholder="192.168.201.10"
                            fullWidth
                            disabled={isConnected}
                            onChange={(ev) => {
                              setIsDirty(true);
                              setAcsIp(ev.target.value || '');
                            }}
                            InputProps={{ className: classes.input }}
                            InputLabelProps={{ className: classes.inputLabel }}
                          />
                        </FormControl>
                      </Paper>

                      <Paper className={classes.paperInput}>
                        <FormControl fullWidth variant="outlined">
                          <TextField
                            variant="outlined"
                            label="Username"
                            value={username}
                            placeholder="Username"
                            fullWidth
                            disabled={isConnected}
                            onChange={(ev) => {
                              setIsDirty(true);
                              setUsername(ev.target.value || '');
                            }}
                            InputProps={{ className: classes.input }}
                            InputLabelProps={{ className: classes.inputLabel }}
                          />
                        </FormControl>
                      </Paper>

                      <Paper className={classes.paperInput}>
                        <FormControl fullWidth variant="outlined">
                          <TextField
                            variant="outlined"
                            label="Password"
                            value={isConnected ? '' : password}
                            placeholder={isConnected ? 'Saved (hidden)' : 'Enter password'}
                            fullWidth
                            type="password"
                            autoComplete="new-password"
                            disabled={isConnected}
                            onChange={(ev) => {
                              setIsDirty(true);
                              setPassword(ev.target.value || '');
                            }}
                            InputProps={{ className: classes.input }}
                            InputLabelProps={{ className: classes.inputLabel }}
                          />
                        </FormControl>
                      </Paper>

                      <br />

                      <Fab
                        variant="extended"
                        size="large"
                        color="primary"
                        style={{ marginLeft: 10, marginBottom: 10 }}
                        aria-label="Login"
                        disabled={
                          isConnected ||
                          acsIp.trim() === '' ||
                          username === '' ||
                          password === ''
                        }
                        onClick={authenticate}
                      >
                        Login
                      </Fab>

                      <Fab
                        variant="extended"
                        size="large"
                        color="secondary"
                        style={{ marginLeft: 10, marginBottom: 10 }}
                        aria-label="Logout"
                        disabled={!isConnected}
                        onClick={handleLogout}
                      >
                        Logout
                      </Fab>
                    </Grid>
                  </Grid>
                </Paper>
              </Paper>
            </Grid>
          </Grid>
        </Grid>

        {rootStore.settings.applicationMode === 6 ? (
          <Grid item xs={12} md={8}>
            <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"
                >
                  ACS01 accounts
                </Typography>
              </Grid>

              <Paper className={classes.paperInput}>
                <Grid container spacing={0}>
                  <Grid
                    item
                    xs={12}
                    style={{
                      height: rootStore.settings.gridHeight,
                      width: '100%',
                    }}
                  >
                    <DataGrid
                      className={classes.dataGrid}
                      rows={rootStore.acs01List.all}
                      rowHeight={80}
                      columns={columns}
                      pageSize={5}
                      checkboxSelection
                      onSelectionModelChange={handleSelectionChange}
                      localeText={{
                        columnMenuSortAsc: t('grid.columnMenuSortAsc'),
                        columnMenuSortDesc: t('grid.columnMenuSortDesc'),
                        columnMenuFilter: t('grid.columnMenuFilter'),
                        columnMenuHideColumn: t('grid.columnMenuHideColumn'),
                        columnMenuShowColumns: t('grid.columnMenuShowColumns'),
                        columnMenuUnsort: t('grid.columnMenuUnsort'),
                        noRowsLabel: t('grid.noRowsLabel'),
                        footerRowSelected: (count) =>
                          count !== 1
                            ? `${count.toLocaleString()} ${t('grid.rowsSelected')}`
                            : `${count.toLocaleString()} ${t('grid.rowSelected')}`,
                      }}
                    />
                  </Grid>
                </Grid>
              </Paper>

              {selectedRows.length > 0 ? (
                <Button
                  variant="contained"
                  color="primary"
                  style={{ backgroundColor: '#f44336' }}
                  onClick={handlePurge}
                >
                  {t('common.Delete-button')}
                </Button>
              ) : null}
            </Paper>
          </Grid>
        ) : null}
      </Grid>
    </div>
  );
}

export default observer(Acs01Config);
