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

import {
  ManifestsProvider,
  useManifestsContext,
} from "../../Contexts/ManifestsContext";
import {
  CarUpdatesProvider,
  useCarUpdatesContext,
} from "../../Contexts/CarUpdatesContext";
import { useUserContext } from "../../Contexts/UserContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import useStyles from "../../useStyles";
import { LocalDateTimeString } from "../../../utils/dates";
import { logger } from "../../../services/monitoring";
import ManifestDetails from "../Details";

const MainForm = () => {
  const { manifest_id } = useParams();
  const classes = useStyles();
  const [pageSize, setPageSize] = useState(10);
  const [pageIndex, setPageIndex] = useState(0);
  const { getManifests, manifests } = useManifestsContext();
  const {
    getCarUpdates,
    carUpdates,
    totalCarUpdates,
    startMonitor,
    stopMonitor,
  } = useCarUpdatesContext();
  const { setMessage, setTitle, setSitePath } = useStatusContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();

  useEffect(() => {
    (async () => {
      try {
        await getManifests({ id: manifest_id }, token);
      } catch (e) {
        setMessage(e.message);
        logger.warn(e.stack);
      }
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [token]);

  useEffect(() => {
    if (!manifests || manifests.length === 0) return;
    const title = `Manifest ${manifests[0].name} ${manifests[0].version}`;
    setTitle(title);
    setSitePath([
      {
        label: "Deployments",
        link: "/packages",
      },
      {
        label: `Deploy ${manifests[0].name} ${manifests[0].version}`,
        link: `/package-deploy/${manifests[0].id}`,
      },
      {
        label: title,
      },
    ]);

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [manifests]);

  useEffect(() => {
    (async () => {
      try {
        stopMonitor();
        await getCarUpdates(
          {
            manifest_id,
            limit: pageSize,
            offset: pageSize * pageIndex,
          },
          token
        );
      } catch (e) {
        setMessage(e.message);
        logger.warn(e.stack);
      }
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pageIndex, pageSize, token]);

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

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

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

  return (
    <div className={clsx(classes.paper, classes.tableSize)}>
      <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" style={{ verticalAlign: "top" }}>
                <Link to={`/vehicle-status/${row.vin}`}>{row.vin}</Link>
              </TableCell>
              <TableCell align="center">
                {row.status}
                {row.progress > -1 && (
                  <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,
              }}
              onPageChange={handleChangePageIndex}
              onRowsPerPageChange={handleChangePageSize}
            />
          </TableRow>
        </TableFooter>
      </Table>
    </div>
  );
};

const ManifestStatus = () => (
  <ManifestsProvider>
    <CarUpdatesProvider>
      <ManifestDetails />
      <MainForm />
    </CarUpdatesProvider>
  </ManifestsProvider>
);

export default ManifestStatus;
