/* eslint-disable radix */
/* eslint-disable no-nested-ternary */
/* eslint-disable react/jsx-props-no-spreading */
import React, { useEffect, useState } from "react";
import {
  Grid,
  Paper,
  Button,
  TextField,
  createTheme,
  darken,
  lighten,
  Theme,
} from "@mui/material";
import { makeStyles } from "@mui/styles";

import { DataGrid, GridColDef, GridToolbar } from "@mui/x-data-grid";
import Typography from "@mui/material/Typography";

import NumberFormat from "react-number-format";
import { observer } from "mobx-react";
import { customAlphabet } from "nanoid";
import { draft } from "mobx-keystone";
import { useTranslation } from "react-i18next";
import User from "../../models/Application/User";
import { getRootStore } from "../../models/root-store.ts";
import Log from "../../models/Logs/Log";

// TODO v5: remove
function getThemePaletteMode(palette: any): string {
  return palette.type || palette.mode;
}

const defaultTheme = createTheme();

const useStylesRows = makeStyles(
  (theme: Theme) => {
    const getBackgroundColor = (color: string) =>
      getThemePaletteMode(theme.palette) === "dark"
        ? darken(color, 0.6)
        : lighten(color, 0.6);

    const getHoverBackgroundColor = (color: string) =>
      getThemePaletteMode(theme.palette) === "dark"
        ? darken(color, 0.5)
        : lighten(color, 0.5);

    return {
      root: {
        border: 0,
        color: "white",
        "& .super-app-theme--Reset": {
          color: "black",
          backgroundColor: getBackgroundColor(theme.palette.info.main),
          "&:hover": {
            backgroundColor: getHoverBackgroundColor(theme.palette.info.main),
          },
        },
        "& .super-app-theme--OK": {
          color: "black",
          backgroundColor: getBackgroundColor(theme.palette.success.main),
          "&:hover": {
            backgroundColor: getHoverBackgroundColor(
              theme.palette.success.main
            ),
          },
        },
        "& .super-app-theme--NoReset": {
          backgroundColor: getBackgroundColor(theme.palette.warning.main),
          "&:hover": {
            backgroundColor: getHoverBackgroundColor(
              theme.palette.warning.main
            ),
          },
        },
        "& .super-app-theme--Fault": {
          backgroundColor: getBackgroundColor(theme.palette.error.main),
          "&:hover": {
            backgroundColor: getHoverBackgroundColor(theme.palette.error.main),
          },
        },
      },
    };
  },
  { defaultTheme }
);
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,
  },
  buttons: {
    backgroundColor: "#666666",
    alignItems: "center",
    alignSelf: "center",
    marginRight: 35,
    minHeight: 70,
    padding: 0,
    margin: 0,
  },
  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: "lightgrey",
    fontSize: "20px",
  },
  inputNumbers: {
    color: "white",
    fontSize: "1.2em",
    padding: "5px",
    width: "auto",
  },
});

function ReportGrid() {
  const classes = useStyles();
  const classesRows = useStylesRows();
  const [rootStore] = useState(() => getRootStore());
  const [rows, setRows] = useState<Log[]>(rootStore.logs.allLogs);
  const [selectedRows, setSelectedRows] = useState<any>([]);

  const { t } = useTranslation();

  const handlePurge = () => {
    rootStore.reportsList.removeReportsByIds(selectedRows);
    setRows(rootStore.logs.allLogs);
    setSelectedRows([]);
  };

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

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

  const columns: GridColDef[] = [
    { field: "date", headerName: "Date", type: "dateTime", width: 150 },
    { field: "counterName", headerName: "Counter name", width: 180 },
    { field: "counterValue", headerName: "Counter value", width: 180 },
    { field: "name", headerName: "Message name", width: 180 },
    { field: "type", headerName: "Type", width: 180 },
    { field: "subType", headerName: "Subtype", width: 130 },
    {
      field: "account",
      headerName: "Came.io account",
      width: 200,
    },
    {
      field: "site",
      headerName: "Came.io site",
      width: 180,
      valueGetter: (cellParams3) => getFullName(cellParams3),
    },
  ];
  return (
    <Paper
      elevation={3}
      className={classes.paperTop}
      style={{
        background: `${rootStore.settings.backgroundColor}`,
        marginBottom: 60,
      }}
    >
      <Paper className={classes.paperInput}>
        <Grid container spacing={0}>
          <Grid
            item
            xs={12}
            style={{
              height: rootStore.settings.gridHeight + 220,
              width: "100%",
            }}
          >
            <DataGrid
              className={classesRows.root}
              rows={rootStore.reportsList.all}
              components={{
                Toolbar: GridToolbar,
              }}
              columns={columns}
              pageSize={10}
              checkboxSelection
              onSelectionModelChange={handleSelectionChange}
              getRowClassName={(params) =>
                `super-app-theme--${params.getValue(params.id, "subType")}`
              }
              sortModel={[
                {
                  field: "date",
                  sort: "desc",
                },
              ]}
              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}
      </Paper>
    </Paper>
  );
}

export default observer(ReportGrid);
