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

import { logger } from "../../../services/monitoring";
import { useStatusContext } from "../../Contexts/StatusContext";
import { useVehicleContext } from "../../Contexts/VehicleContext";
import TableHeaderSortable from "../../Table/HeaderSortable";
import { useLocalStorage } from "../../useLocalStorage";

const tableColumns = [
  {
    id: "car_ecu_name",
    label: "ECU",
  },
  {
    id: "car_ecu_version",
    label: "ECU Supplier Software Version Needed for Next Flashpack Version",
  },
];

const PAGE_SIZE = "ECU_VERSIONS_NEEDED_TABLE_PAGE_SIZE";

const FlashpackInfoTable = ({ vin, token, classes }) => {
  const { setMessage } = useStatusContext();
  const [pageSize, setPageSize] = useLocalStorage(PAGE_SIZE, 10);
  const [pageIndex, setPageIndex] = useState(0);
  const [ecuVersions, setECUVersions] = useState([]);
  const [totalECUVersions, setTotalECUVersions] = useState(0);
  const [flashpackNumber, setFlashpackNumber] = useState("");
  const [nextFlashpackNumber, setNextFlashpackNumber] = useState("");
  const { getCarFlashpackVersionInfo } = useVehicleContext();

  useEffect(() => {
    loadCarFlashpackVersionInfo();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [vin, token, pageIndex, pageSize]);

  const loadCarFlashpackVersionInfo = async () => {
    try {
      if (!vin || !token) return;
      await getCarFlashpackVersionInfo(vin, token)
        .then((result) => {
          setECUVersions(result.data.ecu_versions ? result.data.ecu_versions.slice(pageIndex * pageSize, (pageIndex + 1) * pageSize) : []);
          setTotalECUVersions(result.data.ecu_versions ? result.data.ecu_versions.length : 0)
          setFlashpackNumber(result.data.flashpack);
          setNextFlashpackNumber(result.data.next_flashpack);
        });
    } catch (e) {
      setMessage(e.message);
      logger.warn(e.stack);
    }
  };

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

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

  return (
    <div className={clsx(classes.paper, classes.tableSize)}>
      <Grid container className={classes.root} spacing={2}>
        <Grid item md={12} className={classes.textCenterAlign}>
          <p>
            From Flashpack Version {flashpackNumber ? flashpackNumber : "(none yet)"} to Next Flashpack Version {nextFlashpackNumber ? nextFlashpackNumber : "(none yet)"}
          </p>
        </Grid>
      </Grid>
      {nextFlashpackNumber && (<Table size="small" >
        <TableHeaderSortable
          classes={classes}
          orderBy={"car_ecu_name"}
          order={"asc"}
          columnData={tableColumns}
          onSortRequest={() => { return null }}
        />
        <TableBody>
          {ecuVersions && ecuVersions.map((row, i) => (
            <TableRow key={`${row.car_ecu_name}-${row.car_ecu_version}`}>
              <TableCell align="center">{row.car_ecu_name}</TableCell>
              <TableCell align="center">{row.car_ecu_version}</TableCell>
            </TableRow>
          ))}
        </TableBody>
        <TableFooter>
          <TableRow>
            {!ecuVersions || ecuVersions.length === 0 ? (
              <TableCell colSpan={8} align="center">No ECU Versions to Update for Next Flashpack Version</TableCell>
            ) : (
              <TablePagination
                rowsPerPageOptions={[5, 10, 25, 100]}
                colSpan={4}
                count={totalECUVersions}
                rowsPerPage={pageSize}
                page={pageIndex}
                SelectProps={{
                  inputProps: { "aria-label": "rows per page" },
                  native: true,
                }}
                onPageChange={handleChangePageIndex}
                onRowsPerPageChange={handleChangePageSize}
              />)}
          </TableRow>
        </TableFooter>
      </Table>)}
    </div>
  );
};

export default FlashpackInfoTable;