/* 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,
  Theme,
  createStyles,
  Typography,
  Autocomplete,
} from "@mui/material";
import { makeStyles } from "@mui/styles";

import { observer } from "mobx-react";
import { ipcRenderer } from "electron";
import { useTranslation } from "react-i18next";
// import { locale } from "core-js";
import { DataGrid, GridColDef } from "@mui/x-data-grid";
import { getRootStore } from "../../models/root-store.ts";
import Acs01 from "../../models/Remote/Acs01";
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 Counters() {
  const classes = useStyles();
  const [rootStore] = useState(() => getRootStore());
  const [infoUpdateAvailable, setInfoUpdateAvailable] = React.useState({
    version: "",
    releaseDate: "",
  });
  const [infoUpdateNotAvailable, setInfoUpdateNotAvailable] = React.useState({
    version: "",
    releaseDate: "",
  });
  const [messageUpdate, setMessageUpdate] = React.useState();
  const [updateCheck, setUpdateCheck] = React.useState(false);
  const [updateAvailable, setUpdateAvailable] = React.useState();
  const [selectedStartDate, setSelectedStartDate] = React.useState<
    Date | number | null
  >(rootStore.ticketList.defaultStart);
  const [selectedEndDate, setSelectedEndDate] = React.useState<
    Date | number | null
  >(rootStore.ticketList.defaultEnd);
  const [newTicketLevel, setNewTicketLevel] = React.useState(
    rootStore.settings.ticketLevelToShow
  );
  const [selectedSerialPort, setSelectedSerialPort] = React.useState(
    rootStore.settings.getSerialByPath(rootStore.settings.serialPortPath)
  );
  const [showPassword, setShowPassword] = useState(false);
  const handleClickShowPassword = () => setShowPassword(!showPassword);
  const handleMouseDownPassword = () => setShowPassword(!showPassword);
  const [username, setUsername] = useState<string | undefined>("");
  const [password, setPassword] = useState<string | undefined>("");
  const [isDirty, setIsDirty] = useState(false);
  const [sitesList, setSitesList] = useState<any[]>();
  const [errorLogin, setErrorLogin] = useState(false);
  const [errorSites, setErrorSites] = useState(false);
  const [loginSuccess, setLoginSuccess] = useState<boolean | undefined>();
  const [counterError, setCounterError] = useState<boolean | undefined>();
  const [editMode, setEditMode] = useState(false);
  const [selectedRows, setSelectedRows] = useState<any>([]);
  const [sites, setSites] = useState<any>([]);
  const [siteId, setSiteId] = useState<string>("");
  const [accountId, setAccountId] = useState<string>("");
  const [counters, setCounters] = useState<Counter[]>([]);
  const [acs01, setAcs01] = useState<Acs01>();

  const { t } = useTranslation();

  const handleChangeModule = (event: any, newValue: any) => {
    if (newValue !== null) {
      rootStore.acs01.setLocalName(newValue.name);
      rootStore.acs01.setLocalUrl(newValue.ip);
    }
  };

  const handleChangeSite = (event: any, newValue: any) => {
    if (newValue !== null) {
      setSiteId(newValue.id);
    }
  };

  useEffect(() => {
    ipcRenderer.on("updateAvailable", (event, result) => {
      if (result !== infoUpdateAvailable) {
        setInfoUpdateAvailable(result);
        setUpdateCheck(false);
      }
    });
    ipcRenderer.on("updateNotAvailable", (event, result) => {
      if (result !== infoUpdateNotAvailable) {
        setInfoUpdateNotAvailable(result);
        setUpdateCheck(false);
      }
    });
    ipcRenderer.on("checkingForUpdate", (event, result) => {
      setUpdateCheck(true);
      setTimeout(function () {
        setUpdateCheck(false);
      }, 5000);
    });
    ipcRenderer.on("messageUpdate", (event, result) => {
      setMessageUpdate(result);
    });

    return () => {
      ipcRenderer.removeAllListeners("updateAvailable");
      ipcRenderer.removeAllListeners("updateNotAvailable");
      ipcRenderer.removeAllListeners("checkingForUpdate");
      ipcRenderer.removeAllListeners("messageUpdate");
    };
  });

  const runFetchLoginRemote = async () => {
    console.log("LOGIN ", username);
    console.log("LOGIN ", password);
    const fetchData: any = await fetch(
      `https://sso.came.io/api/sso/account/login?Accept-Bc-version=v2`,
      {
        method: "POST",
        body: JSON.stringify({
          email: username,
          password,
        }),
      }
    )
      .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 runFetchGetSites = async () => {
    const fetchData: any = await fetch(`https://user.came.io/capi/sites`, {
      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 runFetchGetCounters = async () => {
    const fetchData: any = await fetch(
      `https://${siteId.replaceAll("-", "")}.site.came.io/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 runFetchLogout = async () => {
    const fetchData: any = await fetch(
      `https://sso.came.io/api/sso/account/logout`,
      {
        method: "POST",
      }
    )
      .then((response: any) => {
        if (response.status !== 200) {
          return new Error(response.status);
        }
        return response.json();
      })
      .then((json: any) => {
        console.log("logout", json);
        return json;
      })
      .catch((error) => {
        console.log("logout");
        return error;
      });
    return fetchData;
  };

  const authenticate = async () => {
    // Authenticate on the Acs01
    // const loginLocal = await runFetchLoginLocal();
    // console.log("LoginLocal", loginLocal);
    setErrorLogin(false);
    setErrorSites(false);
    setLoginSuccess(undefined);
    setIsDirty(false);

    const loginRemote = await runFetchLoginRemote();
    console.log("loginRemote", loginRemote);
    if (loginRemote?.token) {
      setErrorLogin(false);
      const remoteSites = await runFetchGetSites();
      if (Array.isArray(remoteSites)) {
        setErrorSites(false);
        setLoginSuccess(true);
        setSitesList(remoteSites);
        const remoteCounters = await runFetchGetCounters();
        if (Array.isArray(remoteCounters)) {
          setCounterError(false);
          setCounters(remoteCounters);
        } else {
          setCounterError(true);
        }
      } else {
        setErrorSites(true);
      }
      const logout = await runFetchLogout();
    } else {
      setErrorLogin(true);
    }
  };

  useEffect(() => {
    if (rootStore.counterList.all.length === 0) {
      rootStore.counterList.setConfigured(false);
    } else {
      rootStore.counterList.setConfigured(true);
    }
    return () => {};
  }, [rootStore.counterList]);

  const addCounter = async () => {
    setErrorLogin(false);
    setErrorSites(false);
    setLoginSuccess(undefined);
    rootStore.counterList.set([]);
    if (typeof acs01 !== "undefined") {
      ipcRenderer.send("setSchedulerEnabled", true);
      rootStore.counterList.setConfigured(true);
      counters.map((counter: Counter) => {
        return rootStore.counterList.add(
          new Counter({
            id: counter.id,
            name: counter.name,
            value: counter.value,
            acs01Id: acs01.id,
            siteId,
          })
        );
      });
    }
  };

  /*
      return rootStore.counterList.add(
      new Counter({
        counter.id,
        counter.name,
        acs01,
      })
    );
  */
  const handlePurge = () => {
    rootStore.counterList.removeByIds(selectedRows);
    setSelectedRows([]);
  };

  const handleEdit = () => {
    /*
    const valuesSelection = selectedRows[0];
    const userDraft = draft(rootStore.userList);

    setUserListDraft(userDraft);

    const elementPos = userDraft.data.all
      .map(function (u: User) {
        return u.id;
      })
      .indexOf(valuesSelection);
    setEditMode(true);
    setUserListDraftRowIndex(elementPos);
    setEditId(userDraft.data.all[elementPos].id);
    setEditName(userDraft.data.all[elementPos].name);
    setEditPincode(userDraft.data.all[elementPos].pincode);
    setEditLevel(userDraft.data.all[elementPos].userlevel);
    */
  };

  const handleSelectionChange = (selection: any) => {
    setSelectedRows(selection);
    if (selection.length === 0) {
      setEditMode(false);
    }
  };

  const CustomAvatar = ({ data }: any) => (
    <Card
      raised
      style={{
        backgroundColor: "#d1d1d1",
        display: "flex",
        width: "auto",
        paddingTop: 2,
        paddingLeft: 5,
        paddingRight: 5,
        height: 110,
        margin: 10,
      }}
    >
      <Grid container justifyContent="center" spacing={0}>
        <Grid item xs={12}>
          <Grid container justifyContent="center" spacing={0}>
            <Typography variant="body2">{data.name}</Typography>
          </Grid>
        </Grid>
      </Grid>
    </Card>
  );

  function getFullName(param: any) {
    return rootStore.acs01List.getAcs01ById(param.value?.toString())?.username;
  }

  function getSiteId(param: any) {
    return acs01?.getSiteBySiteId(param.value?.toString())?.name;
  }

  const columns: GridColDef[] = [
    {
      field: "acs01Id",
      headerName: "Account",
      width: 200,
      valueGetter: (cellParams3) => getFullName(cellParams3),
    },
    {
      field: "siteId",
      headerName: "Site",
      width: 200,
      valueGetter: (cellParams3) => getSiteId(cellParams3),
    },
    { field: "name", headerName: t("common.Name"), width: 200 },
    { field: "value", headerName: "value", width: 200 },
    { field: "resetTime", headerName: "reset time", width: 200 },
  ];

  const handleChangeAccount = (event: any, newValue: any) => {
    setSites([]);
    if (newValue !== null) {
      setAcs01(rootStore.acs01List.getAcs01ById(newValue.id));
      setUsername(rootStore.acs01List.getAcs01ById(newValue.id)?.username);
      setPassword(rootStore.acs01List.getAcs01ById(newValue.id)?.password);
      setAccountId(newValue.id);
      setSites(
        rootStore.acs01List.acs01s[
          rootStore.acs01List.getAcs01IndexById(newValue.id)
        ].sitesList
      );
    }
  };

  return (
    <div className={classes.content} data-tid="container">
      <Grid container justifyContent="center" spacing={0}>
        <Grid item xs={12} md={4}>
          <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"
                  >
                    Counter {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">
                        Add counters
                      </Typography>
                      {errorLogin && !isDirty ? (
                        <Card className={classes.feedback}>
                          <Typography
                            style={{ color: "red", marginTop: 20 }}
                            variant="body1"
                          >
                            Access denied.
                          </Typography>
                        </Card>
                      ) : null}
                      {errorSites && !isDirty ? (
                        <Card className={classes.feedback}>
                          <Typography
                            style={{ color: "red", marginTop: 20 }}
                            variant="body1"
                          >
                            Error when loading the sites.
                          </Typography>
                        </Card>
                      ) : null}
                      {counterError && !isDirty ? (
                        <Card className={classes.feedback}>
                          <Typography
                            style={{ color: "red", marginTop: 20 }}
                            variant="body1"
                          >
                            Error when loading the counter data.
                          </Typography>
                        </Card>
                      ) : null}
                      {loginSuccess && !isDirty ? (
                        <Card className={classes.feedback}>
                          <Typography
                            style={{ color: "green", marginTop: 20 }}
                            variant="body1"
                          >
                            Login successful.
                          </Typography>
                        </Card>
                      ) : null}
                      <Paper className={classes.paperInput}>
                        <FormControl fullWidth variant="outlined">
                          <Autocomplete
                            id="Account"
                            options={rootStore.acs01List.all}
                            getOptionLabel={(option) => option.username}
                            onChange={handleChangeAccount}
                            disableClearable
                            selectOnFocus
                            clearOnBlur
                            renderInput={(params) => (
                              <TextField
                                {...params}
                                label="Account"
                                variant="outlined"
                              />
                            )}
                          />
                        </FormControl>
                      </Paper>
                      <br />
                      <Paper className={classes.paperInput}>
                        <FormControl fullWidth variant="outlined">
                          <Autocomplete
                            id="Account"
                            key={sites}
                            options={sites}
                            getOptionLabel={(option) => option.name}
                            onChange={handleChangeSite}
                            disableClearable
                            selectOnFocus
                            clearOnBlur
                            renderInput={(params) => (
                              <TextField
                                {...params}
                                label="Sites"
                                variant="outlined"
                              />
                            )}
                          />
                        </FormControl>
                      </Paper>
                      <br />
                      <Fab
                        variant="extended"
                        size="large"
                        color="primary"
                        style={{ marginLeft: 10, marginBottom: 10 }}
                        aria-label="Connect"
                        disabled={siteId === ""}
                        onClick={authenticate}
                      >
                        Get counters from site
                      </Fab>
                      <Fab
                        variant="extended"
                        size="large"
                        color="secondary"
                        style={{ marginLeft: 10, marginBottom: 10 }}
                        aria-label="Connect"
                        disabled={!loginSuccess || isDirty}
                        onClick={addCounter}
                      >
                        + add
                      </Fab>
                      <br />
                    </Grid>
                  </Grid>
                </Paper>
              </Paper>
            </Grid>
          </Grid>
        </Grid>
        <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"
              >
                Counters to track
              </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.counterList.all}
                    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>
              {selectedRows.length > 0 ? (
                <Button
                  variant="contained"
                  color="primary"
                  style={{ backgroundColor: "#f44336" }}
                  onClick={handlePurge}
                >
                  {t("common.Delete-button")}
                </Button>
              ) : null}
              {selectedRows.length === 1 ? (
                <Button
                  style={{ marginLeft: 20 }}
                  variant="contained"
                  color="primary"
                  onClick={handleEdit}
                >
                  {t("common.Edit-button")}
                </Button>
              ) : null}
            </Paper>
          </Paper>
        </Grid>
      </Grid>
    </div>
  );
}

export default observer(Counters);
