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

import {
  UpdatesProvider,
  useUpdatesContext,
} from "../../Contexts/UpdatesContext";
import { VehicleProvider } from "../../Contexts/VehicleContext";
import { useUserContext } from "../../Contexts/UserContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import useStyles from "../../useStyles";
import { LocalDateTimeString } from "../../../utils/dates";
import TableHeaderSortable from "../../Table/HeaderSortable";
import { logger } from "../../../services/monitoring";

const tableColumns = [
  {
    id: "id",
    label: "ID",
  },
  {
    id: "update_package_id",
    label: "Name",
  },
  {
    id: "status",
    label: "Status",
  },
  {
    id: "created_at",
    label: "Created",
  },
  {
    id: "updated_at",
    label: "Updated",
  },
];

const MainForm = () => {
  const { vin } = useParams();
  const classes = useStyles();
  const [pageSize, setPageSize] = useState(10);
  const [pageIndex, setPageIndex] = useState(0);
  const [orderBy, setOrderBy] = useState("id");
  const [order, setOrder] = useState("desc");
  const { getCarUpdates, carUpdates, totalCarUpdates } = useUpdatesContext();
  const { setMessage, setTitle } = useStatusContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();

  useEffect(() => {
    setTitle(`Vehicle ${vin} Details`);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [vin]);

  useEffect(() => {
    (async () => {
      try {
        await getCarUpdates(
          {
            vin,
            limit: pageSize,
            offset: pageSize * pageIndex,
            order: `${orderBy} ${order}`,
          },
          token
        );
      } catch (e) {
        setMessage(e.message);
        logger.warn(e.stack);
      }
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pageIndex, pageSize, token, 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={classes.paper} style={{ height: 700, width: "100%" }}>
      <Table>
        <TableHeaderSortable
          classes={classes}
          orderBy={orderBy}
          order={order}
          columnData={tableColumns}
          onSortRequest={handleSort}
        />
        <TableBody>
          {carUpdates.map((row) => (
            <TableRow key={row.id}>
              <TableCell align="center">{row.id}</TableCell>
              <TableCell align="center">{`${row.updatepackage.package_name} ${row.updatepackage.version}`}</TableCell>
              <TableCell align="center">{row.status}</TableCell>
              <TableCell align="center">
                {LocalDateTimeString(row.created)}
              </TableCell>
              <TableCell align="center">
                {LocalDateTimeString(row.updated)}
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
        <TableFooter>
          <TableRow>
            <TablePagination
              rowsPerPageOptions={[5, 10, 25, 100]}
              colSpan={5}
              count={totalCarUpdates}
              rowsPerPage={pageSize}
              page={pageIndex}
              SelectProps={{
                inputProps: { "aria-label": "rows per page" },
                native: true,
              }}
              onChangePage={handleChangePageIndex}
              onChangeRowsPerPage={handleChangePageSize}
            />
          </TableRow>
        </TableFooter>
      </Table>
    </div>
  );
};

const CarUpdates = () => (
  <VehicleProvider>
    <UpdatesProvider>
      <MainForm />
    </UpdatesProvider>
  </VehicleProvider>
);

export default CarUpdates;
