import {
  IconButton,
  Table,
  TableBody,
  TableCell,
  TableFooter,
  TablePagination,
  TableRow,
} from "@material-ui/core";
import DeleteIcon from "@material-ui/icons/Delete";
import { logger } from "../../services/monitoring";
import React, { useEffect, useState } from "react";
import { useParams } from "react-router";
import {
  CarUpdatesProvider,
  useCarUpdatesContext
} 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: "sums_version",
    label: "SUMS Version",
  },
  {
    id: "sums_rxswin",
    label: "RXSwin Version",
  },
];

const PAGE_SIZE = "SUMS_RXSWIN_TABLE_PAGE_SIZE";

const MainForm = () => {
  const { sums_version } = useParams();
  const classes = useStyles();
  const [pageSize, setPageSize] = useLocalStorage(PAGE_SIZE, 10);
  const [pageIndex, setPageIndex] = useState(0);
  const [orderBy, setOrderBy] = useState("id");
  const [order, setOrder] = useState("desc");
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [rowToDelete, setRowToDelete] = useState({});
  const {
    deleteSUMSVersionRxSwins,
    getSUMSVersionRxSwins,
    versionRxSwins,
    stopMonitor,
  } = useCarUpdatesContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
    groups,
    providers,
  } = useUserContext();
  const { setMessage } = useStatusContext();

  useEffect(() => {
    (async () => {
      try {
        if (!sums_version || !token) return;
        stopMonitor();
        await getSUMSVersionRxSwins(
          sums_version,
          token
        );
      } catch (e) {
        setMessage(e.message);
        logger.warn(e.stack);
      }
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [sums_version, token]);

  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 {
        await deleteSUMSVersionRxSwins(rowToDelete.version, rowToDelete.rxswin, token);
        setMessage(`Sent delete for ${rowToDelete.rxswin}`);
      } catch (e) {
        setMessage(e.message);
      }
    }
  };

  return (
    <div>
      <Table>
        <TableHeaderSortable
          classes={classes}
          orderBy={orderBy}
          order={order}
          columnData={tableColumns}
          onSortRequest={handleSort}
        />
        <TableBody>
          {versionRxSwins.map((row, index) => (
            <TableRow key={index}>
              <TableCell align="center">
                {row.version}
              </TableCell>
              <TableCell align="center">
                {row.rxswin}
              </TableCell>
              <TableCell>
                <RoleWrap
                  groups={groups}
                  providers={providers}
                  rolesPerProvider={Permissions.FiskerMagnaCreate}
                >
                  <IconButton
                    onClick={() => onDeleteClick(row)}
                    aria-label={`Send delete for ${row.rxswin}`}
                    size="small"
                    color="primary"
                  >
                    <DeleteIcon aria-label={`Delete ${row.rxswin}`} />
                  </IconButton>
                </RoleWrap>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
        <TableFooter>
          <TableRow>
            {versionRxSwins.length === 0 ? (
              <TableCell colSpan={8} align="center">No RX Identification Numbers</TableCell>
            ) : (
              <TablePagination
                rowsPerPageOptions={[5, 10, 25, 100]}
                colSpan={8}
                count={versionRxSwins.length}
                rowsPerPage={pageSize}
                page={pageIndex}
                SelectProps={{
                  inputProps: { "aria-label": "rows per page" },
                  native: true,
                }}
                onPageChange={handleChangePageIndex}
                onRowsPerPageChange={handleChangePageSize}
              />)}
          </TableRow>
        </TableFooter>
      </Table>
      <DeleteConfirmation
        message={rowToDelete && rowToDelete.rxswin ? rowToDelete.rxswin : ""}
        open={showDeleteModal}
        close={() => setShowDeleteModal(false)}
        deleteFunction={sendDelete}
      />
    </div>
  );
};

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

export default SumsRxSwin;