import React, { useEffect, useState } from "react";
import { Link } from 'react-router-dom';
import {
  Grid,
  Table,
  TableBody,
  TableCell,
  TableFooter,
  TablePagination,
  TableRow,
  Tooltip,
} from "@material-ui/core";
import AddCircleIcon from "@material-ui/icons/AddCircle";
import DeleteIcon from "@material-ui/icons/Delete";
import clsx from "clsx";

import TableHeaderSortable from "../../../../Table/HeaderSortable";
import { useUserContext } from "../../../../Contexts/UserContext"
import { useStatusContext } from "../../../../Contexts/StatusContext";
import { FleetProvider, useFleetContext } from "../../../../Contexts/FleetContext"
import useStyles from "../../../../useStyles";
import SearchField from "../../../../Controls/SearchField";
import { logger } from "../../../../../services/monitoring";
import { Roles, hasRole } from "../../../../../utils/roles";
import { useLocalStorage } from "../../../../useLocalStorage";
import DeleteConfirmation from "../../../../DeleteConfirmation";

const tableColumns = [
  {
    id: "vin",
    label: "VIN"
  },
  {
    id: "",
    label: "Actions"
  }
];

const PAGE_SIZE = "FLEET_STATUS_VEHICLES_TABLE_PAGE_SIZE";

const MainForm = ({ name }) => {
  const [pageSize, setPageSize] = useLocalStorage(PAGE_SIZE, 10);
  const [pageIndex, setPageIndex] = useState(0);
  const [orderBy, setOrderBy] = useState("id");
  const [order, setOrder] = useState("desc");
  const [search, setSearch] = useState("");
  const [showDeleteModal, setShowDeleteModal] = useState(false)
  const classes = useStyles();
  const { setMessage } = useStatusContext();
  const { fleetVehicles, totalFleetVehicles, getFleetVehicles, deleteFleetVehicle } = useFleetContext();
  const { token: { idToken: { jwtToken: token } }, groups } = useUserContext();

  const handleSearch = (query) => {
    setSearch(query);
  };

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

  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 onDelete = async (vin) => {
    try {
      await deleteFleetVehicle(name, { vin: vin }, token);
      setMessage(`Deleted ${vin}`)
    } catch (e) {
      setMessage(e.message);
      logger.warn(e.stack);
    }
  };

  const Actions = (vin) => {
    let actions = [];
    if (hasRole([Roles.DELETE], groups)) {
      actions.push({
        tip: `Delete "${vin}"`,
        id: vin,
        icon: <DeleteIcon aria-label={`Delete ${vin}`} />
      })
    }
    if (actions.length === 0) return ["No actions"];

    return actions.map((action) => {
      if (action.link != null) {
        return (
          <Tooltip key={action.link} title={action.tip}>
            <Link to={action.link} style={{ margin: 5 }}>
              {action.icon}
            </Link>
          </Tooltip>
        );
      } else {
        return (
          <span key={`delete-${action.id}-of-div`}>
            <Tooltip key={`delete-${action.id}`} title={action.tip}>
              <Link to="#" onClick={() => onDelete(action.id)}>
                {action.icon}
              </Link>
            </Tooltip>
            <DeleteConfirmation message={action.id} open={showDeleteModal} close={() => setShowDeleteModal(false)} deleteFunction={() => onDelete(action.id)} />
          </span>

        );
      }
    });
  };

  return (
    <div className={clsx(classes.paper, classes.tableSize)}>
      <Grid container className={classes.root} spacing={2}>
        <Grid item md={4} className={classes.textJustifyAlign}>
          <Link to={`/fleet/${name}/vehicle-add`} className={classes.labelInline}>
            <AddCircleIcon fontSize="large" />
          </Link>
        </Grid>
        <Grid item md={8} align="right" className={classes.textCenterAlign}>
          <SearchField classes={classes} onSearch={handleSearch} />
        </Grid>
      </Grid>
      <Table>
        <TableHeaderSortable
          classes={classes}
          orderBy={orderBy}
          order={order}
          columnData={tableColumns}
          onSortRequest={handleSort}
        />
        <TableBody>
          {fleetVehicles.map(vin => (
            <TableRow key={vin}>
              <TableCell align="center">
                <Link to={`/vehicle-status/${vin}`}>{vin}</Link>
              </TableCell>
              <TableCell align="center">{Actions(vin)}</TableCell>
            </TableRow>
          ))}
        </TableBody>
        <TableFooter>
          <TableRow>
            <TablePagination
              rowsPerPageOptions={[5, 10, 25, 100]}
              colSpan={8}
              count={totalFleetVehicles}
              rowsPerPage={pageSize}
              page={pageIndex}
              SelectProps={{
                inputProps: { "aria-label": "rows per page" },
                native: true,
              }}
              onPageChange={handleChangePageIndex}
              onRowsPerPageChange={handleChangePageSize}
            />
          </TableRow>
        </TableFooter>
      </Table>
    </div >
  );
};

const FleetVehiclesTable = (props) => (
  <FleetProvider>
    <MainForm {...props} />
  </FleetProvider>
);

export default FleetVehiclesTable;
