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

import { useSupplierContext } from "../../Contexts/SupplierContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import { LocalDateTimeString } from "../../../utils/dates";
import TableHeaderSortable from "../../Table/HeaderSortable";
import { logger } from "../../../services/monitoring";
import { useLocalStorage } from "../../useLocalStorage";

const tableColumns = [
  {
    id: "contact",
    label: "Contact",
  },
  {
    id: "company",
    label: "Company",
  },
  {
    id: "email",
    label: "Email",
  },
  {
    id: "program",
    label: "Program",
  },
  {
    id: "ecus",
    label: "ECUs",
  },
  {
    id: "created_at",
    label: "Registered",
  },
  {
    id: "activated_at",
    label: "Activated",
  },
  {
    id: "signin_at",
    label: "Sign In",
  },
  {
    id: "keys_at",
    label: "Keys",
  },
];

const PAGE_SIZE = "SUPPLIER_TABLE_PAGE_SIZE";

const SupplierTable = (props) => {
  const { token, classes } = props;
  const [pageSize, setPageSize] = useLocalStorage(PAGE_SIZE, 10);
  const [pageIndex, setPageIndex] = useState(0);
  const [orderBy, setOrderBy] = useState("created_at");
  const [order, setOrder] = useState("asc");
  const { getSuppliers, suppliers, totalSuppliers } = useSupplierContext();
  const { setMessage } = useStatusContext();

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

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

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

  const query = async (signal) => {
    try {
      const options = {
        limit: pageSize,
        offset: pageSize * pageIndex,
        order: `${orderBy} ${order}`,
      };
      await getSuppliers(options, token, signal);
    } catch (e) {
      setMessage(e.message);
      logger.warn(e.stack);
    }
  };

  useEffect(() => {
    const controller = new AbortController();

    query(controller.signal);

    return () => {
      controller.abort();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pageIndex, pageSize, orderBy, order, token]);

  return (
    <div className={clsx(classes.paper, classes.tableSize)}>
      <Table>
        <TableHeaderSortable
          classes={classes}
          orderBy={orderBy}
          order={order}
          columnData={tableColumns}
          onSortRequest={sortHandler}
          rowCount={suppliers ? suppliers.length : 0}
        />
        <TableBody>
          {suppliers.map((row, index) => {
            const ecuList = row.ecus.join(", ");
            return (
              <TableRow key={index}>
                <TableCell align="center">
                  <Link to={`/supplier/${row.email}`}>{row.contact}</Link>
                </TableCell>
                <TableCell align="center">{row.company}</TableCell>
                <TableCell align="center">
                  <a href={`mailto:${row.email}`}>{row.email}</a>
                </TableCell>
                <TableCell align="center">{row.program}</TableCell>
                <TableCell align="center">
                  <Tooltip title={ecuList}>
                    <span className={classes.truncateCell}>
                      {ecuList}
                    </span>
                  </Tooltip>
                </TableCell>
                <TableCell align="center">
                  {LocalDateTimeString(row.created)}
                </TableCell>
                <TableCell align="center">
                  {LocalDateTimeString(row.activated)}
                </TableCell>
                <TableCell align="center">
                  {LocalDateTimeString(row.signin_at)}
                </TableCell>
                <TableCell align="center">
                  {LocalDateTimeString(row.keys_at)}
                </TableCell>
              </TableRow>
            );
          })}
        </TableBody>
        <TableFooter>
          <TableRow>
            <TablePagination
              rowsPerPageOptions={[5, 10, 25, 100]}
              colSpan={9}
              count={totalSuppliers}
              rowsPerPage={pageSize}
              page={pageIndex}
              SelectProps={{
                inputProps: { "aria-label": "rows per page" },
                native: true,
              }}
              onPageChange={handleChangePageIndex}
              onRowsPerPageChange={handleChangePageSize}
            />
          </TableRow>
        </TableFooter>
      </Table>
    </div>
  );
};

SupplierTable.propTypes = {
  token: PropTypes.string.isRequired,
  classes: PropTypes.object.isRequired,
};

export default SupplierTable;
