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

import {
  UpdatesProvider,
  useUpdatesContext,
} from "../../Contexts/UpdatesContext";
import { useUserContext } from "../../Contexts/UserContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import useStyles from "../../useStyles";
import { LocalDateTimeString } from "../../../utils/dates";
import VehicleStatus from "../../Cars/StatusModal";

const MainForm = () => {
  const { packageid } = useParams();
  const classes = useStyles();
  const [pageSize, setPageSize] = useState(10);
  const [pageIndex, setPageIndex] = useState(0);
  const [viewVIN, setViewVIN] = useState(null);
  const {
    getCarUpdates,
    carUpdates,
    totalCarUpdates,
    getPackages,
    packages,
    startMonitor,
    stopMonitor,
  } = useUpdatesContext();
  const { setMessage, setTitle } = useStatusContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();

  useEffect(() => {
    try {
      getPackages({ id: packageid }, token);
    } catch (e) {
      setMessage(e.message);
    }
    // eslint-disable-next-line
  }, [token]);

  useEffect(() => {
    if (!packages || packages.length === 0) return;
    setTitle(`Package ${packages[0].package_name} ${packages[0].version}`);

    // eslint-disable-next-line
  }, [packages]);

  useEffect(() => {
    try {
      stopMonitor();
      getCarUpdates(
        {
          packageid,
          limit: pageSize,
          offset: pageSize * pageIndex,
        },
        token
      );
    } catch (e) {
      setMessage(e.message);
    }
    // eslint-disable-next-line
  }, [pageIndex, pageSize, token]);

  useEffect(() => {
    try {
      if (carUpdates.length === 0) return;
      startMonitor(token);
    } catch (e) {
      setMessage(e.message);
    }
    return () => {
      stopMonitor();
    };
    // eslint-disable-next-line
  }, [carUpdates]);

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

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

  const handleViewVIN = (event) => {
    event.preventDefault();
    setViewVIN(event.target.innerHTML);
  };

  const handleCloseViewVIN = (event) => {
    setViewVIN(null);
  };

  return (
    <div className={classes.paper} style={{ height: 700, width: "100%" }}>
      <TableContainer>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell align="center">ID</TableCell>
              <TableCell align="center">Vehicle</TableCell>
              <TableCell align="center">Status</TableCell>
              <TableCell align="center">Created</TableCell>
              <TableCell align="center">Updated</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {carUpdates.map((row) => (
              <TableRow key={row.id}>
                <TableCell align="center">{row.id}</TableCell>
                <TableCell align="center">
                  <span className={classes.link} onClick={handleViewVIN}>
                    {row.vin}
                  </span>
                </TableCell>
                <TableCell align="center">
                  {row.status}
                  {row.progress > 0 && (
                    <LinearProgress
                      variant="determinate"
                      value={row.progress}
                    />
                  )}
                </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>
      </TableContainer>
      <VehicleStatus vin={viewVIN} handleClose={handleCloseViewVIN} />
    </div>
  );
};

const CarUpdatesStatus = () => (
  <UpdatesProvider>
    <MainForm />
  </UpdatesProvider>
);

export default CarUpdatesStatus;
