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 clsx from "clsx";
import { LocalDateTimeString } from "../../utils/dates";
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 { Link } from "react-router-dom";
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: "rxswin",
    label: "RXSWIN (RX Software Identification Number)",
  },
  {
    id: "created_at",
    label: "Created",
  },
  {
    id: "delete",
    label: "Delete",
  },
];

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("created_at");
  const [order, setOrder] = useState("desc");
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [rowToDelete, setRowToDelete] = useState({});
  const {
    deleteSUMSVersionRxSwins,
    getSUMSVersionRxSwins,
    versionRxSwins,
    totalVersionRxSwins,
    stopMonitor,
  } = useCarUpdatesContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
    groups,
    providers,
  } = useUserContext();
  const { setMessage, setTitle, setSitePath } = useStatusContext();

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

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

  const loadSUMSVersionRxSwins = async () => {
    try {
      if (!sums_version || !token) return;
      stopMonitor();
      await getSUMSVersionRxSwins(
        sums_version,
        {
          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 deleteSUMSVersionRxSwins(rowToDelete.version, rowToDelete.rxswin, token);
        if (!result || result.error) return;

        setMessage(`Deleted ${rowToDelete.rxswin}`);
        loadSUMSVersionRxSwins();
      } 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-rxswin-add/${sums_version}`} className={classes.labelInline}>
            <AddCircleIcon fontSize="large" />
          </Link>
        </Grid>
      </Grid>
      <Table>
        <TableHeaderSortable
          classes={classes}
          orderBy={orderBy}
          order={order}
          columnData={tableColumns}
          onSortRequest={handleSort}
        />
        <TableBody>
          {versionRxSwins && versionRxSwins.map((row, index) => (
            <TableRow key={index}>
              <TableCell align="center">
                {row.rxswin}
              </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.rxswin}`}
                    size="small"
                    color="primary"
                  >
                    <DeleteIcon aria-label={`Delete ${row.rxswin}`} />
                  </IconButton>
                </RoleWrap>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
        <TableFooter>
          <TableRow>
            {!versionRxSwins || versionRxSwins.length === 0 ? (
              <TableCell colSpan={8} align="center">No RX Software Identification Numbers</TableCell>
            ) : (
              <TablePagination
                rowsPerPageOptions={[5, 10, 25, 100]}
                colSpan={3}
                count={totalVersionRxSwins}
                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;