import React, { useEffect, useState } from "react";
import {
  Table,
  TableBody,
  TableCell,
  TableFooter,
  TablePagination,
  TableRow,
} from "@material-ui/core";

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

const tableColumns = [
  {
    id: "created_at",
    label: "Date",
  },
  {
    id: "status",
    label: "Status",
  },
  {
    id: "info",
    label: "Info",
  },
  {
    id: "error_code",
    label: "Error",
  },
];

const PAGE_SIZE = "CAR_UPDATE_STATUS_TABLE_PAGE_SIZE";

const CarUpdateStatusTable = ({ carupdateid, token }) => {
  const classes = useStyles();
  const [log, setLog] = useState([]);
  const [logTotal, setLogTotal] = useState(0);
  const [pageSize, setPageSize] = useLocalStorage(PAGE_SIZE, 10);
  const [pageIndex, setPageIndex] = useState(0);
  const [orderBy, setOrderBy] = useState("id");
  const [order, setOrder] = useState("desc");
  const { getLog } = useCarUpdatesContext();
  const { setMessage } = useStatusContext();

  useEffect(() => {
    (async () => {
      try {
        if (!carupdateid || !token) return;
        const result = await getLog(
          {
            carupdateid,
            limit: pageSize,
            offset: pageSize * pageIndex,
            order: `${orderBy} ${order}`,
          },
          token
        );
        setLog(result.data);
        if (pageIndex === 0 && result.total) setLogTotal(result.total);
      } catch (e) {
        setMessage(e.message);
        logger.warn(e.stack);
      }
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [carupdateid, token, pageIndex, pageSize, orderBy, order]);

  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);
    }
  };

  return (
    <Table>
      <TableHeaderSortable
        classes={classes}
        orderBy={orderBy}
        order={order}
        columnData={tableColumns}
        onSortRequest={handleSort}
      />
      <TableBody>
        {log.map((row) => (
          <TableRow key={row.id}>
            <TableCell align="center">
              {LocalDateTimeString(row.created)}
            </TableCell>
            <TableCell align="center">{row.status}</TableCell>
            <TableCell align="center">{row.info}</TableCell>
            <TableCell align="center">{row.error}</TableCell>
          </TableRow>
        ))}
      </TableBody>
      <TableFooter>
        <TableRow>
          <TablePagination
            rowsPerPageOptions={[5, 10, 25, 100]}
            colSpan={5}
            count={logTotal}
            rowsPerPage={pageSize}
            page={pageIndex}
            SelectProps={{
              inputProps: { "aria-label": "rows per page" },
              native: true,
            }}
            onPageChange={handleChangePageIndex}
            onRowsPerPageChange={handleChangePageSize}
          />
        </TableRow>
      </TableFooter>
    </Table>
  );
};

export default CarUpdateStatusTable;
