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

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

const tableColumns = [
  {
    id: "ecu",
    label: "ECU",
  },
  {
    id: "sw_version",
    label: "SW Version",
  },
  {
    id: "hw_version",
    label: "HW Version",
  },
  {
    id: "vendor",
    label: "Vendor",
  },
  {
    id: "supplier_sw_version",
    label: "Supplier Version",
  },
  {
    id: "serial_number",
    label: "Serial",
  },
  {
    id: "boot_loader_version",
    label: "Boot Loader",
  },
  {
    id: "fingerprint",
    label: "Fingerprint",
  },
  {
    id: "updated_at",
    label: "Updated",
  },
];

const PAGE_SIZE = "CAR_ECUS_TABLE_PAGE_SIZE";

const CarECUsTable = ({ vin, token, classes }) => {
  const [ecus, setECUs] = useState([]);
  const [total, setTotal] = useState(0);
  const [pageSize, setPageSize] = useLocalStorage(PAGE_SIZE, 10);
  const [pageIndex, setPageIndex] = useState(0);
  const [orderBy, setOrderBy] = useState("ecu");
  const [order, setOrder] = useState("desc");
  const { getECUs } = useVehicleContext();
  const { setMessage } = useStatusContext();

  useEffect(() => {
    (async () => {
      try {
        if (!vin || !token) return;
        const result = await getECUs(
          {
            vin,
            limit: pageSize,
            offset: pageSize * pageIndex,
            order: `${orderBy} ${order}`,
          },
          token
        );
        setECUs(result.data);
        if (result.total > -1) setTotal(result.total);
      } catch (e) {
        setMessage(e.message);
        logger.warn(e.stack);
      }
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [vin, token, pageIndex, pageSize, orderBy, order]);

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

  return (
    <div className={clsx(classes.paper, classes.tableSize)}>
      <Table>
        <TableHeaderSortable
          classes={classes}
          orderBy={orderBy}
          order={order}
          columnData={tableColumns}
          onSortRequest={handleSort}
        />
        <TableBody>
          {ecus.map((row, i) => (
            <TableRow key={row.ecu + i}>
              {tableColumns.map((column, j) => {
                const key = `${row.ecu + i}${column.id}`
                if (column.id === "updated_at") return (<TableCell key={key} align="center">{LocalDateTimeString(row.updated)}</TableCell>);
                return (
                  <TableCell key={key} align="center" className={classes.limitWidthTableCell}>
                    <Tooltip title={`${row[column.id] || 'none'}`}>
                      <span>{row[column.id]}</span>
                    </Tooltip>
                  </TableCell>
                );
              })}
            </TableRow>
          ))}
        </TableBody>
        <TableFooter>
          <TableRow>
            <TablePagination
              rowsPerPageOptions={[5, 10, 25, 100]}
              colSpan={10}
              count={total}
              rowsPerPage={pageSize}
              page={pageIndex}
              SelectProps={{
                inputProps: { "aria-label": "rows per page" },
                native: true,
              }}
              onPageChange={handleChangePageIndex}
              onRowsPerPageChange={handleChangePageSize}
            />
          </TableRow>
        </TableFooter>
      </Table>
    </div>
  );
};

export default CarECUsTable;
