import {
  Table,
  TableBody,
  TableCell,
  TableFooter,
  TablePagination,
  TableRow
} from "@material-ui/core";
import DeleteIcon from "@material-ui/icons/Delete";
import clsx from "clsx";
import PropTypes from "prop-types";
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";

import { logger } from "../../../services/monitoring";
import { LocalDateTimeString } from "../../../utils/dates";
import { Permissions } from "../../../utils/roles";
import { useIssueContext } from "../../Contexts/IssueContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import { useUserContext } from "../../Contexts/UserContext";
import TableHeaderSortable from "../../Table/HeaderSortable";
import { useLocalStorage } from "../../useLocalStorage";
import { RoleWrap } from "../RoleWrap";

const tableColumns = [
  {
    id: "id",
    label: "Id",
  },
  {
    id: "vin",
    label: "VIN",
  },
  {
    id: "title",
    label: "Title",
  },
  {
    id: "driver_id",
    label: "Driver ID",
  },
  {
    id: "created_at",
    label: "Created",
  },
  {
    id: "",
    label: "",
  },
];

const PAGE_SIZE = "ISSUE_SELECTION_TABLE_PAGE_SIZE";

const IssueSelectionTable = (props) => {
  const {
    token,
    classes,
    search,
    multiSelect,
    selected,
    onSelectAll,
  } = props;

  const [pageSize, setPageSize] = useLocalStorage(PAGE_SIZE, 10);
  const [pageIndex, setPageIndex] = useState(0);
  const [orderBy, setOrderBy] = useState("created_at");
  const [order, setOrder] = useState("desc");
  const { deleteIssue, getIssues, issues, totalIssues = 0 } = useIssueContext();
  const { groups, providers } = useUserContext();
  const { setMessage } = useStatusContext();

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

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

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

  const handleSelectAll = (event) => {
    if (!onSelectAll) return;

    const newSelected = [];
    if (event.target.checked) {
      issues.forEach((car) => {
        newSelected.push(car.vin);
      });
    }

    onSelectAll(newSelected);
  };

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

  useEffect(() => {
    setPageIndex(0);
  }, [search]);

  const handleDelete = (id) => {
    deleteIssue(id, token).then(() => {
      const options = {
        limit: pageSize,
        offset: pageSize * pageIndex,
        order: `${orderBy} ${order}`,
      };
      getIssues(Object.assign(options, search), token);
    });
  };

  return (
    <div className={clsx(classes.paper, classes.tableSize)}>
      <Table>
        <TableHeaderSortable
          classes={classes}
          orderBy={orderBy}
          order={order}
          columnData={tableColumns}
          onSortRequest={handleSort}
          multiSelect={multiSelect}
          onSelectAll={handleSelectAll}
          selectCount={selected ? selected.length : 0}
          rowCount={issues ? issues.length : 0}
        />
        <TableBody>
          {issues.map((row) => {
            return (
              <TableRow key={row.id}>
                <TableCell align="center">
                  <Link to={`/issue-info/${row.id}`}>{row.id}</Link>
                </TableCell>
                <TableCell align="center">{row.vin}</TableCell>
                <TableCell align="center">{row.title}</TableCell>
                <TableCell align="center">{row.driver_id}</TableCell>
                <TableCell align="center">
                  {LocalDateTimeString(row.timestamp)}
                </TableCell>
                <RoleWrap
                  groups={groups}
                  providers={providers}
                  rolesPerProvider={Permissions.FiskerDelete}
                >
                  <TableCell>
                    <Link to="#" onClick={() => handleDelete(row.id)}>
                      <DeleteIcon />
                    </Link>
                  </TableCell>
                </RoleWrap>
              </TableRow>
            );
          })}
        </TableBody>
        <TableFooter>
          <TableRow>
            <TablePagination
              rowsPerPageOptions={[5, 10, 25, 100]}
              colSpan={6}
              count={totalIssues}
              rowsPerPage={pageSize}
              page={pageIndex}
              SelectProps={{
                inputProps: { "aria-label": "rows per page" },
                native: true,
              }}
              onPageChange={handleChangePageIndex}
              onRowsPerPageChange={handleChangePageSize}
            />
          </TableRow>
        </TableFooter>
      </Table>
    </div>
  );
};

IssueSelectionTable.propTypes = {
  token: PropTypes.string.isRequired,
  classes: PropTypes.object.isRequired,
  multiSelect: PropTypes.bool,
  selected: PropTypes.array,
  onSelect: PropTypes.func,
  onSelectAll: PropTypes.func,
};

export default IssueSelectionTable;