import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableFooter,
  TableHead,
  TablePagination,
  TableRow,
  Tooltip,
  Typography,
} from "@material-ui/core";
import EditIcon from "@material-ui/icons/Edit";
import SendIcon from "@material-ui/icons/Send";
import VisibilityIcon from "@material-ui/icons/Visibility";
import useStyles from "../../useStyles";
import {
  UpdatesProvider,
  useUpdatesContext,
} from "../../Contexts/UpdatesContext";
import { useUserContext } from "../../Contexts/UserContext";
import { tsLocalDateTimeString } from "../../../utils/dates";
import { Roles, hasRole } from "../../../utils/roles";

const UpdatePackagesList = () => {
  const classes = useStyles();
  const [pageSize, setPageSize] = useState(5);
  const [pageIndex, setPageIndex] = useState(0);
  const { getPackages, packages, totalPackages } = useUpdatesContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
    groups,
  } = useUserContext();

  useEffect(() => {
    getPackages({ limit: pageSize, offset: pageSize * pageIndex }, token);
    // eslint-disable-next-line
  }, [pageIndex, pageSize, token]);

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

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

  const Actions = (row) => {
    let actions = [];
    if (hasRole([Roles.CREATE, Roles.READ], groups)) {
      actions.push({
        tip: `Status "${row.package_name} ${row.version}"`,
        link: `/carupdate-status/${row.id}`,
        icon: (
          <VisibilityIcon
            aria-label={`Status ${row.package_name} ${row.version}`}
          />
        ),
      });
    }
    if (hasRole([Roles.CREATE], groups)) {
      actions = actions.concat([
        {
          tip: `Edit "${row.package_name} ${row.version}"`,
          link: `/update/${row.id}`,
          icon: (
            <EditIcon aria-label={`Edit ${row.package_name} ${row.version}`} />
          ),
        },
        {
          tip: `Deploy "${row.package_name} ${row.version}"`,
          link: `/carupdate-deploy/${row.id}`,
          icon: (
            <SendIcon
              aria-label={`Deploy ${row.package_name} ${row.version}`}
            />
          ),
        },
      ]);
    }

    if (actions.length === 0) return "No actions";

    return actions.map((action) => (
      <Tooltip key={action.link} title={action.tip}>
        <Link to={action.link} style={{ margin: 5 }}>
          {action.icon}
        </Link>
      </Tooltip>
    ));
  };

  return (
    <div className={classes.paper} style={{ height: 700, width: "100%" }}>
      <Typography component="h1" variant="h5">
        Updates
      </Typography>
      <TableContainer>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell align="center">ID</TableCell>
              <TableCell align="center">Name</TableCell>
              <TableCell align="center">Version</TableCell>
              <TableCell align="center">Created</TableCell>
              <TableCell align="right">Actions</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {packages.map((row) => (
              <TableRow key={row.id}>
                <TableCell align="center">{row.id}</TableCell>
                <TableCell align="center">{row.package_name}</TableCell>
                <TableCell align="center">{row.version}</TableCell>
                <TableCell align="center">
                  {tsLocalDateTimeString(row.timestamp)}
                </TableCell>
                <TableCell align="right">{Actions(row)}</TableCell>
              </TableRow>
            ))}
          </TableBody>
          <TableFooter>
            <TableRow>
              <TablePagination
                rowsPerPageOptions={[5, 10, 25]}
                colSpan={5}
                count={totalPackages}
                rowsPerPage={pageSize}
                page={pageIndex}
                SelectProps={{
                  inputProps: { "aria-label": "rows per page" },
                  native: true,
                }}
                onChangePage={handleChangePageIndex}
                onChangeRowsPerPage={handleChangePageSize}
              />
            </TableRow>
          </TableFooter>
        </Table>
      </TableContainer>
    </div>
  );
};

const UpdatePackagesForm = () => (
  <UpdatesProvider>
    <UpdatePackagesList />
  </UpdatesProvider>
);

export default UpdatePackagesForm;
