import {
  Grid,
  Table,
  TableBody,
  TableCell,
  TableFooter,
  TablePagination,
  TableRow,
  Tooltip,
} from "@material-ui/core";
import DeleteIcon from "@material-ui/icons/Delete";
import SendIcon from "@material-ui/icons/Send";
import VisibilityIcon from "@material-ui/icons/Visibility";
import clsx from "clsx";
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";

import EditIcon from "@material-ui/icons/Edit";
import { logger } from "../../../services/monitoring";
import { LocalDateTimeString } from "../../../utils/dates";
import { TYPE_MANIFEST_SOFTWARE } from "../../../utils/manifest_types";
import { hasRole, Permissions } from "../../../utils/roles";
import {
  ManifestsProvider,
  useManifestsContext,
} from "../../Contexts/ManifestsContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import { useUserContext } from "../../Contexts/UserContext";
import ECUList from "../../Controls/ECUList";
import SearchField from "../../Controls/SearchField";
import DeleteConfirmation from "../../DeleteConfirmation";
import TableHeaderSortable from "../../Table/HeaderSortable";
import { useLocalStorage } from "../../useLocalStorage";
import useStyles from "../../useStyles";

const tableColumns = [
  {
    id: "id",
    label: "ID",
  },
  {
    id: "name",
    label: "Name",
  },
  {
    id: "version",
    label: "Version",
  },
  {
    id: "type",
    label: "Type",
  },
  {
    id: "created_at",
    label: "Created",
  },
  {
    id: "updated_at",
    label: "Updated",
  },
  {
    id: "",
    label: "Actions",
  },
];

const formatManifestType = (type) => {
  switch (type) {
    case "forced":
      return "Forced";
    default:
      return "Standard";
  }
};

const PAGE_SIZE = "MANIFEST_LIST_PAGE_SIZE";

const MainForm = () => {
  const classes = useStyles();
  const [pageSize, setPageSize] = useLocalStorage(PAGE_SIZE, 10);
  const [pageIndex, setPageIndex] = useState(0);
  const [orderBy, setOrderBy] = useState("id");
  const [order, setOrder] = useState("asc");
  const [search, setSearch] = useState("");

  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [deleteId, setDeleteId] = useState("");
  const [deleteRowName, setDeleteRowName] = useState("");

  const { getManifests, deleteManifest, manifests, totalManifests } =
    useManifestsContext();
  const { setMessage, setTitle, setSitePath } = useStatusContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
    groups,
    providers,
  } = useUserContext();

  const sortHandler = (event, property) => {
    if (property === orderBy) {
      if (order === "asc") {
        setOrder("desc");
      } else {
        setOrder("asc");
      }
    } else {
      setOrderBy(property);
      setOrder("asc");
    }
  };

  useEffect(() => {
    setTitle("Deployments");
    setSitePath([]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    (async () => {
      try {
        await getManifests(
          {
            limit: pageSize,
            offset: pageSize * pageIndex,
            order: `${orderBy} ${order}`,
            manifest_type: TYPE_MANIFEST_SOFTWARE,
            search,
          },
          token
        );
      } catch (e) {
        setMessage(e.message);
        logger.warn(e.stack);
      }
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pageIndex, pageSize, token, orderBy, order, search]);

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

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

  const handleSearch = (query) => {
    setPageIndex(0);
    setSearch(query);
  };

  const setDeletePopup = (id, row) => {
    setDeleteId(id);
    setDeleteRowName(`${row.name} ${row.version}`);
    setShowDeleteModal(true);
  };

  const onDelete = async (manifest_id) => {
    try {
      await deleteManifest(parseInt(manifest_id), token);
    } catch (e) {
      setMessage(e.message);
      logger.warn(e.stack);
    }
  };

  const Actions = (row) => {
    let actions = [];
    if (hasRole(groups, Permissions.FiskerMagnaRead, providers)) {
      actions.push({
        tip: `Status "${row.name} ${row.version}"`,
        link: `/package-status/${row.id}`,
        icon: (
          <VisibilityIcon aria-label={`Status ${row.name} ${row.version}`} />
        ),
      });
    }
    if (hasRole(groups, Permissions.FiskerRead, providers)) {
      actions.push({
        tip: `Update "${row.name} ${row.version}"`,
        link: `/package-update/${row.id}`,
        icon: <EditIcon aria-label={`Update ${row.name} ${row.version}`} />,
      });
    }
    if (hasRole(groups, Permissions.FiskerMagnaCreate, providers)) {
      actions.push({
        tip: `Deploy "${row.name} ${row.version}"`,
        link: `/package-deploy/${row.id}`,
        icon: <SendIcon aria-label={`Deploy ${row.name} ${row.version}`} />,
      });
    }
    if (hasRole(groups, Permissions.FiskerDelete, providers)) {
      actions.push({
        tip: `Delete "${row.name} ${row.version}"`,
        id: row.id,
        icon: <DeleteIcon aria-label={`Delete ${row.name} ${row.version}`} />,
      });
    }
    if (actions.length === 0) return ["No actions"];

    return actions.map((action) => {
      if (action.link != null) {
        return (
          <Tooltip key={action.link} title={action.tip}>
            <Link to={action.link} style={{ margin: 5 }}>
              {action.icon}
            </Link>
          </Tooltip>
        );
      } else {
        return (
          <span key={`delete-${action.id}-of-key`}>
            <Tooltip key={`delete-${action.id}`} title={action.tip}>
              <Link to="#" onClick={() => setDeletePopup(action.id, row)}>
                {action.icon}
              </Link>
            </Tooltip>
          </span>
        );
      }
    });
  };

  return (
    <div className={clsx(classes.paper, classes.tableSize)}>
      <Grid container className={classes.root} spacing={2}>
        <Grid item md={4} className={classes.textJustifyAlign}></Grid>
        <Grid item md={4} className={classes.textCenterAlign}>
          <SearchField classes={classes} onSearch={handleSearch} />
        </Grid>
        <Grid item md={4} className={classes.textRightAlign}></Grid>
      </Grid>
      <Table>
        <TableHeaderSortable
          classes={classes}
          orderBy={orderBy}
          order={order}
          columnData={tableColumns}
          onSortRequest={sortHandler}
        />
        <TableBody>
          {manifests.map((row) => (
            <TableRow key={row.id}>
              <TableCell align="center">{row.id}</TableCell>
              <TableCell align="center">
                {row.name}
                {row.ecu_list && (
                  <>
                    <br />
                    <ECUList
                      list={row.ecu_list}
                      search={search}
                      searchedOnly={true}
                    />
                  </>
                )}
              </TableCell>
              <TableCell align="center">{row.version}</TableCell>
              <TableCell align="center">
                {formatManifestType(row.type)}
              </TableCell>
              <TableCell align="center">
                {LocalDateTimeString(row.created)}
              </TableCell>
              <TableCell align="center">
                {LocalDateTimeString(row.updated)}
              </TableCell>
              <TableCell align="center">{Actions(row)}</TableCell>
            </TableRow>
          ))}
        </TableBody>
        <TableFooter>
          <TableRow>
            <TablePagination
              rowsPerPageOptions={[5, 10, 25, 100]}
              colSpan={6}
              count={totalManifests}
              rowsPerPage={pageSize}
              page={pageIndex}
              SelectProps={{
                inputProps: { "aria-label": "rows per page" },
                native: true,
              }}
              onPageChange={handleChangePageIndex}
              onRowsPerPageChange={handleChangePageSize}
            />
          </TableRow>
        </TableFooter>
      </Table>
      <DeleteConfirmation
        message={deleteRowName}
        open={showDeleteModal}
        close={() => setShowDeleteModal(false)}
        deleteFunction={() => onDelete(deleteId)}
      />
    </div>
  );
};

const ManifestsList = () => (
  <ManifestsProvider>
    <MainForm />
  </ManifestsProvider>
);

export default ManifestsList;
