import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableFooter,
  TablePagination,
  TableRow,
  Tooltip
} from "@material-ui/core";
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: "flashpack_number",
    label: "Flashpack Number",
  },
  {
    id: "sw_version",
    label: "SW Version (F188)",
  },
  {
    id: "hw_version",
    label: "HW Version (F191)",
  },
  {
    id: "vendor",
    label: "Vendor (F18A)",
  },
  {
    id: "supplier_sw_version",
    label: "Supplier Version (F195)",
  },
  {
    id: "serial_number",
    label: "Serial (F18C)",
  },
  {
    id: "boot_loader_version",
    label: "Boot Loader (F183)",
  },
  {
    id: "code_data_string",
    label: "Config (F108)",
  },
  {
    id: "fingerprint",
    label: "Fingerprint (F184)",
  },
  {
    id: "assy_number",
    label: "ASSY Number (F187)",
  },
  {
    id: "updated_at",
    label: "Updated",
  },
  {
    id: "epoch_usec",
    label: "Epoch",
  },
];

const PAGE_SIZE = "CAR_ECUS_TABLE_PAGE_SIZE";

const CarECUsTable = ({ vin, token, classes, search, unique }) => {
  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,
            search,
            unique,
            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, search, unique]);

  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 (
    <TableContainer>
      <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>
    </TableContainer>
  );
};

export default CarECUsTable;
