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

import TableHeaderSortable from "../../Table/HeaderSortable";
import {useStatusContext} from "../../Contexts/StatusContext";
import {useFleetContext} from "../../Contexts/FleetContext"
import {logger} from "../../../services/monitoring";
import {useLocalStorage} from "../../useLocalStorage";
import PropTypes from "prop-types";

const tableColumns = [
  {
    id: "name",
    label: "Name"
  },
  {
    id: "log_level",
    label: "Log Level"
  },
  {
    id: "canbus_enabled",
    label: "CAN Bus Enabled"
  },
  {
    id: "data_logger_enabled",
    label: "Data Logger Enabled"
  },
  {
    id: "num_vehicles",
    label: "Vehicles"
  },
  {
    id: "num_filters",
    label: "Filters"
  }
];

const PAGE_SIZE = "FLEET_SELECTION_TABLE_PAGE_SIZE";

const FleetSelectionTable = (props) => {
  const {
    token,
    classes,
    search,
    multiSelect,
    selected,
    onSelect,
    onSelectAll,
  } = props;

  const [pageSize, setPageSize] = useLocalStorage(PAGE_SIZE, 10);
  const [pageIndex, setPageIndex] = useState(0);
  const [orderBy, setOrderBy] = useState("id");
  const [order, setOrder] = useState("desc");
  const { fleets, getFleets, totalFleets } = useFleetContext();
  const { setMessage } = useStatusContext();
  const { search: searchTerm } = search;

  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 handleChangePageIndex = (_event, newIndex) => {
    setPageIndex(newIndex);
  };

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

  const handleSelectAll = (event) => {
    if (!onSelectAll) return;

    const newSelected = [];
    if (event.target.checked) {
      fleets.forEach((car) => {
        newSelected.push(car.name);
      });
    }

    onSelectAll(newSelected);
  };

  const handleSelect = (event, key) => {
    if (!onSelect) return;

    onSelect(event, key);
  };


  useEffect(() => {
    const options = { search: searchTerm,
        limit: pageSize,
        offset: pageSize * pageIndex,
        order: `${orderBy} ${order}`,
    };
    (async () => {
      try {
        if (!token) return;
        await getFleets(options, token);
      } catch (e) {
        setMessage(e.message);
        logger.warn(e.stack);
      }
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [token, pageIndex, pageSize, orderBy, order, searchTerm]);

  return (
    <div className={clsx(classes.paper, classes.tableSize)}>
      <Table>
        <TableHeaderSortable
          classes={classes}
          orderBy={orderBy}
          order={order}
          columnData={tableColumns}
          onSortRequest={handleSort}
          multiSelect={multiSelect}
          onSelectAll={handleSelectAll}
          selectCount={selected ? selected.length : 0}
          rowCount={fleets ? fleets.length : 0}
        />
        <TableBody>
          {fleets.map((row) => {
              const isSelected = selected
                ? selected.indexOf(row.name) !== -1
                : false;
              return (
                <TableRow key={row.name}>
                  {multiSelect && (
                    <TableCell padding="checkbox">
                      <Checkbox
                        checked={isSelected}
                        onChange={(event) => handleSelect(event, row.name)}
                      />
                    </TableCell>
                  )}
                  <TableCell align="center">
                    <Link to={`/fleet/${row.name}`}>{row.name}</Link>
                  </TableCell>
                  <TableCell align="center">{row.log_level}</TableCell>
                  <TableCell align="center">{row.canbus.enabled ? "true" : "false"}</TableCell>
                  <TableCell align="center">{row.canbus.data_logger_enabled ? "true" : "false"}</TableCell>
                  <TableCell align="center">{!row.vehicles ? 0 : row.vehicles.length}</TableCell>
                  <TableCell align="center">{!row.canbus.filters ? 0 : row.canbus.filters.length}</TableCell>
                </TableRow>)
            }
          )}
        </TableBody>
        <TableFooter>
          <TableRow>
            <TablePagination
              rowsPerPageOptions={[5, 10, 25, 100]}
              colSpan={8}
              count={totalFleets}
              rowsPerPage={pageSize}
              page={pageIndex}
              SelectProps={{
                inputProps: {"aria-label": "rows per page"},
                native: true,
              }}
              onPageChange={handleChangePageIndex}
              onRowsPerPageChange={handleChangePageSize}
            />
          </TableRow>
        </TableFooter>
      </Table>
    </div>
  );
};

FleetSelectionTable.propTypes = {
  token: PropTypes.string.isRequired,
  classes: PropTypes.object.isRequired,
  search: PropTypes.object.isRequired,
  multiSelect: PropTypes.bool.isRequired,
  selected: PropTypes.array,
  onSelect: PropTypes.func,
  onSelectAll: PropTypes.func,
  connectionStatus: PropTypes.bool,
}

export default FleetSelectionTable;
