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

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

const PAGE_SIZE = "MANIFEST_STATUS_PAGE_SIZE";

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

const MainForm = () => {
  const { manifest_id } = useParams();
  const classes = useStyles();
  const [pageSize, setPageSize] = useLocalStorage(PAGE_SIZE, 10);
  const [pageIndex, setPageIndex] = useState(0);
  const [orderBy, setOrderBy] = useState("id");
  const [order, setOrder] = useState("desc");
  const [ids, setIds] = useState([]);
  const { getManifests, manifests } = useManifestsContext();
  const {
    getCarUpdates,
    carUpdates,
    totalCarUpdates,
    startMonitor,
    stopMonitor,
  } = useCarUpdatesContext();
  const { setMessage, setTitle, setSitePath } = useStatusContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();

  const handleSelectAll = () => {
    setIds((ids) => ids.length === 0
      ? carUpdates.map((carUpdate) => carUpdate.id)
      : []);
  }

  const handleSelect = (newId, selected) => {
    if (selected) {
      setIds((ids) => ids.filter((id) => id !== newId));
    } else {
      setIds((ids) => [...ids, newId]);
    }
  }

  const handleSort = (_event, property) => {
    if (property === orderBy) {
      if (order === "asc") {
        setOrder("desc");
      } else {
        setOrder("asc");
      }
    } else {
      setOrderBy(property);
      setOrder("asc");
    }
  };

  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,
            order: `${orderBy} ${order}`,
          },
          token
        );
      } catch (e) {
        setMessage(e.message);
        logger.warn(e.stack);
      }
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pageIndex, pageSize, token, order, orderBy]);

  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)}>
      <Grid container className={classes.root} spacing={2}>
        <Grid item md={8} className={classes.textJustifyAlign}>
          <ManifestDetails />
        </Grid>
        <Grid item md={4} className={classes.textRightAlign}>
          <BulkActions ids={ids} actions={["cancel", "redeploy"]} />
        </Grid>
      </Grid>
      <Table>
        <TableHeaderSortable
          classes={classes}
          orderBy={orderBy}
          order={order}
          columnData={tableColumns}
          onSortRequest={handleSort}
          multiSelect={true}
          onSelectAll={handleSelectAll}
          selectCount={ids ? ids.length : 0}
          rowCount={carUpdates ? carUpdates.length : 0}
        />
        <TableBody>
          {carUpdates.map((row) => {
            const isSelected = ids.indexOf(row.id) !== -1;
            return (
              <TableRow key={row.id}>
                <TableCell padding="checkbox">
                  <Checkbox
                    checked={isSelected}
                    onChange={() => handleSelect(row.id, isSelected)}
                  />
                </TableCell>
                <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={6}
              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>
      <MainForm />
    </CarUpdatesProvider>
  </ManifestsProvider>
);

export default ManifestStatus;
