import {
  Grid,
  IconButton,
  Table,
  TableBody,
  TableCell,
  TableFooter,
  TablePagination,
  TableRow,
} from "@material-ui/core";
import AddCircleIcon from "@material-ui/icons/AddCircle";
import DeleteIcon from "@material-ui/icons/Delete";
import { LocalDateTimeString } from "../../../utils/dates";
import clsx from "clsx";
import { Link } from "react-router-dom";
import { logger } from "../../../services/monitoring";
import React, { useEffect, useState } from "react";
import { useCarUpdatesContext, CarUpdatesProvider } from "../../Contexts/CarUpdatesContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import { useUserContext } from "../../Contexts/UserContext";
import TableHeaderSortable from "../../Table/HeaderSortable";
import { useLocalStorage } from "../../useLocalStorage";
import DeleteConfirmation from "../../DeleteConfirmation";
import useStyles from "../../useStyles";
import { Permissions } from "../../../utils/roles";
import { RoleWrap } from "../../Controls/RoleWrap";

const tableColumns = [
  {
    id: "version",
    label: "SUMS Version",
  },
  {
    id: "os_version",
    label: "OS Version",
  },
  {
    id: "created_at",
    label: "Created",
  },
  {
    id: "delete",
    label: "Delete",
  },
];

const PAGE_SIZE = "SUMS_VERSIONS_TABLE_PAGE_SIZE";

const MainForm = () => {
  const classes = useStyles();
  const { setMessage, setTitle, setSitePath } = useStatusContext();
  const [orderBy, setOrderBy] = useState("version");
  const [order, setOrder] = useState("desc");
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [rowToDelete, setRowToDelete] = useState({});
  const [pageSize, setPageSize] = useLocalStorage(PAGE_SIZE, 10);
  const [pageIndex, setPageIndex] = useState(0);
  const {
    getSUMSVersionsList,
    deleteSUMSVersion,
    versions,
    totalVersions,
    stopMonitor,
  } = useCarUpdatesContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
    groups,
    providers,
  } = useUserContext();

  useEffect(() => {
    setTitle("SUMS Versions");
    setSitePath([
      {
        label: "Tools",
        link: "/tools/sumsversions",
      },
      {
        label: "SUMS Versions",
      },
    ]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    loadSUMSVersions();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [token, pageIndex, pageSize, orderBy, order]);

  const loadSUMSVersions = async () => {
    try {
      if (!token) return;
      stopMonitor();
      await getSUMSVersionsList(
        {
          limit: pageSize,
          offset: pageSize * pageIndex,
          order: `${orderBy} ${order}`,
        },
        token
      );
    } catch (e) {
      setMessage(e.message);
      logger.warn(e.stack);
    }
  };

  const handleChangePageIndex = (event, newIndex) => {
    setPageIndex(newIndex);
  };

  const handleChangePageSize = (event) => {
    setPageSize(parseInt(event.target.value, 10));
    setPageIndex(0);
  };

  const handleSort = (event, property) => {
    try {
      if (property === orderBy) {
        if (order === "asc") {
          setOrder("desc");
        } else {
          setOrder("asc");
        }
      } else {
        setOrderBy(property);
        setOrder("asc");
      }
    } catch (e) {
      logger.warn(e.stack);
    }
  };

  const onDeleteClick = (row) => {
    setRowToDelete(row);
    setShowDeleteModal(true);
  }

  const sendDelete = async () => {
    if (rowToDelete) {
      try {
        const result = await deleteSUMSVersion(rowToDelete.version, token);
        if (!result || result.error) return;

        setMessage(`Deleted ${rowToDelete.version}`);
        loadSUMSVersions();
      } catch (e) {
        setMessage(e.message);
        logger.warn(e.stack);
      }
    }
  };

  return (
    <div>
      <Grid container className={classes.root} spacing={2}>
        <Grid item md={4} className={clsx(classes.textJustifyAlign, classes.actionsBar)}>
          <Link to={`/tools/sums/new`} className={classes.labelInline}>
            <AddCircleIcon fontSize="large" />
          </Link>
        </Grid>
      </Grid>
      <Table>
        <TableHeaderSortable
          classes={classes}
          orderBy={orderBy}
          order={order}
          columnData={tableColumns}
          onSortRequest={handleSort}
        />
        <TableBody>
          {versions && versions.map((row, index) => (
            <TableRow key={row.version + row.os_version}>
              <TableCell align="center">
                <Link to={`/tools/sums/${row.version}`}>
                  {row.version}
                </Link>
              </TableCell>
              <TableCell align="center">
                {row.os_version}
              </TableCell>
              <TableCell align="center">
                {LocalDateTimeString(row.created)}
              </TableCell>
              <TableCell>
                <RoleWrap
                  groups={groups}
                  providers={providers}
                  rolesPerProvider={Permissions.FiskerMagnaDelete}
                >
                  <IconButton
                    onClick={() => onDeleteClick(row)}
                    aria-label={`Send delete for ${row.version}`}
                    size="small"
                    color="primary"
                  >
                    <DeleteIcon aria-label={`Delete ${row.version}`} />
                  </IconButton>
                </RoleWrap>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
        <TableFooter>
          <TableRow>
            {!versions || versions.length === 0 ? (
              <TableCell colSpan={8} align="center">No SUMS Versions</TableCell>
            ) : (
              <TablePagination
                rowsPerPageOptions={[5, 10, 25, 100]}
                colSpan={4}
                count={totalVersions}
                rowsPerPage={pageSize}
                page={pageIndex}
                SelectProps={{
                  inputProps: { "aria-label": "rows per page" },
                  native: true,
                }}
                onPageChange={handleChangePageIndex}
                onRowsPerPageChange={handleChangePageSize}
              />)}
          </TableRow>
        </TableFooter>
      </Table>
      <DeleteConfirmation
        message={rowToDelete && rowToDelete.version ? rowToDelete.version : ""}
        open={showDeleteModal}
        close={() => setShowDeleteModal(false)}
        deleteFunction={sendDelete}
      />
    </div>
  );
};

const SUMS = () => (
  <CarUpdatesProvider>
    <MainForm />
  </CarUpdatesProvider>
);

export default SUMS;