import {
  IconButton,
  LinearProgress,
  Table,
  TableBody,
  TableCell,
  TableFooter,
  TablePagination,
  TableRow,
} from "@material-ui/core";
import CancelIcon from "@material-ui/icons/Cancel";
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";

import { logger } from "../../../services/monitoring";
import { LocalDateTimeString } from "../../../utils/dates";
import { Permissions } from "../../../utils/roles";
import {
  CarUpdatesProvider,
  useCarUpdatesContext
} from "../../Contexts/CarUpdatesContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import { useUserContext } from "../../Contexts/UserContext";
import TableHeaderSortable from "../../Table/HeaderSortable";
import { useLocalStorage } from "../../useLocalStorage";
import useStyles from "../../useStyles";
import { RoleWrap } from "../RoleWrap";

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

const PAGE_SIZE = "CAR_UPDATES_TABLE_PAGE_SIZE";

const MainForm = ({ vin, token }) => {
  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 {
    cancelUpdate,
    getCarUpdates,
    carUpdates,
    totalCarUpdates,
    startMonitor,
    stopMonitor,
  } = useCarUpdatesContext();
  const { setMessage } = useStatusContext();

  const { groups, providers } = useUserContext();

  useEffect(() => {
    (async () => {
      try {
        if (!vin || !token) return;
        stopMonitor();
        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
  }, [vin, token, pageIndex, pageSize, orderBy, order]);

  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);
  };

  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);
    }
  };

  const updateName = (row) => {
    if (row.updatemanifest)
      return `${row.updatemanifest.name} ${row.updatemanifest.version}`;
    return "None";
  };

  const sendCancel = async (row) => {
    try {
      await cancelUpdate(row.id, token);
      setMessage(`Sent cancel for ${updateName(row)}`);
    } catch (e) {
      setMessage(e.message);
    }
  };

  return (
    <Table>
      <TableHeaderSortable
        classes={classes}
        orderBy={orderBy}
        order={order}
        columnData={tableColumns}
        onSortRequest={handleSort}
      />
      <TableBody>
        {carUpdates.map((row, index) => (
          <TableRow key={index}>
            <TableCell align="center">{row.id}</TableCell>
            <TableCell align="center">
              <Link to={`/vehicle-status/${row.vin}/${row.id}`}>
                {updateName(row)}
              </Link>
            </TableCell>
            <TableCell align="center">
              {row.updatemanifest?.sums}
            </TableCell>
            <TableCell align="center">
              {row.username}
            </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>
            <TableCell>
              <RoleWrap
                groups={groups}
                providers={providers}
                rolesPerProvider={Permissions.FiskerMagnaCreate}
              >
                <IconButton
                  onClick={() => sendCancel(row)}
                  aria-label={`Send cancel for ${row.vin}`}
                  size="small"
                  color="primary"
                >
                  <CancelIcon fontSize="inherit" />
                </IconButton>
              </RoleWrap>
            </TableCell>
          </TableRow>
        ))}
      </TableBody>
      <TableFooter>
        <TableRow>
          {totalCarUpdates === 0 ? (
            <TableCell colSpan={8} align="center">No Car Updates</TableCell>
          ) : (
            <TablePagination
              rowsPerPageOptions={[5, 10, 25, 100]}
              colSpan={8}
              count={totalCarUpdates}
              rowsPerPage={pageSize}
              page={pageIndex}
              SelectProps={{
                inputProps: { "aria-label": "rows per page" },
                native: true,
              }}
              onPageChange={handleChangePageIndex}
              onRowsPerPageChange={handleChangePageSize}
            />)}
        </TableRow>
      </TableFooter>
    </Table>
  );
};

const CarUpdatesTable = (props) => (
  <CarUpdatesProvider>
    <MainForm {...props} />
  </CarUpdatesProvider>
);

export default CarUpdatesTable;
