/* 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,
  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({
  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,
  },
  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 EntryUnit = observer(() => {
  const classes = useStyles();
  const [rootStore] = useState(() => getRootStore());
  const [errorLogin, setErrorLogin] = useState(false);
  const [errorNoAccount, setErrorNoAccount] = 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.printerList.defaultPrinterId !== "undefined" &&
        typeof rootStore.printerList.defaultPrinter !== "undefined" &&
        rootStore.printerList.defaultPrinterId !== ""
      ) {
        const getPrinter = await ipcRenderer.invoke('printerById', [
          rootStore.acs01List?.defaultAcs01.localUrl,
          rootStore.printerList?.defaultPrinterId,
        ]);
        if (getPrinter) rootStore.printerList.setDefaultPrinter(getPrinter);
        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);
      }
      if (rootStore.terminal.useParkingCounterLogic) {
        const getCounters = await ipcRenderer.invoke('getCounters', rootStore.acs01List?.defaultAcs01.localUrl);
        if (Array.isArray(getCounters)) {
          rootStore.counterList.setFromAcs(getCounters); // assuming setFromAcs exists and processes the API format
        } else {
          setErrorLogin(true); // fallback
        }
      }
      
      return "OK";
    }
    rootStore.acs01List.setLocalStatus(0);
    setErrorLogin(true);
    return new Error();
  };

  return (
    <>
      {rootStore.acs01List.defaultAcs01 &&
      rootStore.acs01List.defaultAcs01?.localName !== "" ? (
        <>
          <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}` }}
              >
                <Paper className={classes.paperInput}>
                  <Grid item xs={12}>
                    <Typography
                      className={classes.content}
                      variant="h6"
                      component="span"
                    >
                      Print ticket when on loop
                    </Typography>
                    <Switch
                      checked={rootStore.terminal.ticketOnLoop}
                      onChange={async () => {
                        rootStore.terminal.setTicketOnLoop(
                          !rootStore.terminal.ticketOnLoop
                        );
                      }}
                      inputProps={{ "aria-label": "controlled" }}
                    />
                  </Grid>
                </Paper>
              

                <Paper className={classes.paperInput}>
  <Grid item xs={12}>
    <Typography
      className={classes.content}
      variant="h6"
      component="span"
    >
      Set parking to close if this counter is not 0 
    </Typography>
    <Switch
      checked={rootStore.terminal.useParkingCounterLogic}
      
      onChange={async () => {
        const newValue = !rootStore.terminal.useParkingCounterLogic;
        rootStore.terminal.setUseParkingCounterLogic(newValue);
        if (newValue) {
          await authenticate(); // load counters immediately
        }
      }}
      
      
      
      
      inputProps={{ "aria-label": "Enable counter logic" }}
    />
  </Grid>
</Paper>

{rootStore.terminal.useParkingCounterLogic && (
  <Grid item xs={12}>
    <Paper className={classes.paperInputNested}>
      <Typography style={{ color: "white" }}>
        Counters loaded: {rootStore.counterList.all.length}
      </Typography>

      <Autocomplete
        id="CounterSelector"
        value={
          rootStore.counterList.all.find(
            (c) => c.id === rootStore.terminal.counterIdToCheck
          ) || null
        }
        options={rootStore.counterList.all}
        getOptionLabel={(option) => option.name || option.id || "Unnamed Counter"}
        onChange={async (event: any, newValue: any) => {
          if (newValue) {
            rootStore.terminal.setCounterIdToCheck(newValue.id);
            await authenticate(); // if needed
          }
        }}
        isOptionEqualToValue={(option, value) => option.id === value.id}
        renderInput={(params) => (
          <TextField
            {...params}
            label="Select Counter"
            variant="outlined"
          />
        )}
      />
    </Paper>
  </Grid>
)}









              </Paper>
            </Grid>
          </Grid>
        </>
      ) : null}
    </>
  );
});

export default EntryUnit;
