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

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

const tableColumns = [
  {
    id: "version_source",
    label: "Type",
  },
  {
    id: "version",
    label: "Version",
  },
  {
    id: "created_at",
    label: "Date",
  },
];

const PAGE_SIZE = "CAR_VERSIONLOG_TABLE_PAGE_SIZE";

const CarVersionLogTable = ({ vin, token, classes }) => {
  const [versions, setVersions] = useState([]);
  const [total, setTotal] = useState(0);
  const [pageSize, setPageSize] = useLocalStorage(PAGE_SIZE, 10);
  const [pageIndex, setPageIndex] = useState(0);
  const [orderBy, setOrderBy] = useState("created_at");
  const [order, setOrder] = useState("desc");
  const { getVersionLog } = useVehicleContext();
  const { setMessage } = useStatusContext();

  useEffect(() => {
    (async () => {
      try {
        if (!vin || !token) return;
        const result = await getVersionLog(
          {
            vin,
            limit: pageSize,
            offset: pageSize * pageIndex,
            order: `${orderBy} ${order}`,
          },
          token
        );
        setVersions(result.data);
        if (result.total > -1) setTotal(result.total);
      } catch (e) {
        setMessage(e.message);
        logger.warn(e.stack);
      }
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [vin, 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 (
    <div className={clsx(classes.paper, classes.tableSize)}>
      <Table>
        <TableHeaderSortable
          classes={classes}
          orderBy={orderBy}
          order={order}
          columnData={tableColumns}
          onSortRequest={handleSort}
        />
        <TableBody>
          {versions && versions.map((row, i) => (
            <TableRow key={`row${i}`}>
              <TableCell align="center">{row.version_source}</TableCell>
              <TableCell align="center">{row.version}</TableCell>
              <TableCell align="center">{LocalDateTimeString(row.created_at)}</TableCell>
            </TableRow>
          ))}
        </TableBody>
        <TableFooter>
          <TableRow>
            <TablePagination
              rowsPerPageOptions={[5, 10, 25, 100]}
              colSpan={3}
              count={total}
              rowsPerPage={pageSize}
              page={pageIndex}
              SelectProps={{
                inputProps: { "aria-label": "rows per page" },
                native: true,
              }}
              onPageChange={handleChangePageIndex}
              onRowsPerPageChange={handleChangePageSize}
            />
          </TableRow>
        </TableFooter>
      </Table>
    </div>
  );
};

export default CarVersionLogTable;
