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 EditIcon from "@material-ui/icons/Edit";
import clsx from "clsx";
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";

import { logger } from "../../../services/monitoring";
import { hasRole, Permissions } from "../../../utils/roles";
import { trimIfMoreThan } from "../../../utils/strings";
import {
  CANFiltersProvider,
  useCANFiltersContext,
} from "../../Contexts/CANFiltersContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import { useUserContext } from "../../Contexts/UserContext";
import SearchField from "../../Controls/SearchField";
import TableHeaderSortable from "../../Table/HeaderSortable";
import { useLocalStorage } from "../../useLocalStorage";
import useStyles from "../../useStyles";

const tableColumns = [
  {
    id: "can_id",
    label: "CAN ID",
  },
  {
    id: "interval",
    label: "Interval (ms)",
  },
  {
    id: "fleet",
    label: "Fleet",
  },
  {
    id: "edge_mask",
    label: "Edge mask",
  },
  {
    id: "",
    label: "Actions",
  },
];

const PAGE_SIZE = "CAN_FILTER_TABLE_PAGE_SIZE";

const MainForm = ({ vin }) => {
  const classes = useStyles();
  const [search, onSearch] = useState("");
  const [pageSize, setPageSize] = useLocalStorage(PAGE_SIZE, 10);
  const [pageIndex, setPageIndex] = useState(0);
  const [orderBy, setOrderBy] = useState("id");
  const [order, setOrder] = useState("desc");
  const { getFilters, deleteFilter, filters, totalFilters } =
    useCANFiltersContext();
  const { setMessage } = useStatusContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
    groups,
    providers,
  } = useUserContext();

  useEffect(() => {
    (async () => {
      try {
        if (!vin || !token) return;
        await getFilters(
          vin,
          {
            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
  }, [vin, 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 (can_id) => {
    try {
      await deleteFilter(vin, can_id, token);
      setMessage(`Deleted ${can_id}`);
    } catch (e) {
      setMessage(e.message);
      logger.warn(e.stack);
    }
  };

  const Actions = (row) => {
    if (row.fleet != null) {
      return;
    }

    let actions = [];
    if (hasRole(groups, Permissions.FiskerCreate, providers)) {
      let link = `/filter-update?vin=${vin}&can_id=${row.can_id}`;
      if (row.interval || row.interval===0) {
        link = link + `&interval=${row.interval}`
      }
      if (row.edge_mask) {
        link = link + `&edge_mask=${row.edge_mask}`
      }
      actions.push({
        tip: `Update "${row.can_id}"`,
        link,
        icon: <EditIcon aria-label={`Update ${row.can_id}`} />,
      });
    }
    if (hasRole(groups, Permissions.FiskerDelete, providers)) {
      actions.push({
        tip: `Delete "${row.can_id}"`,
        id: row.can_id,
        icon: <DeleteIcon aria-label={`Delete ${row.can_id}`} />,
      });
    }
    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 (
          <Tooltip key={`delete-${action.id}`} title={action.tip}>
            <Link to="#" onClick={() => onDelete(action.id)}>
              {action.icon}
            </Link>
          </Tooltip>
        );
      }
    });
  };

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

const CANFiltersTable = (props) => (
  <CANFiltersProvider>
    <MainForm {...props} />
  </CANFiltersProvider>
);

export default CANFiltersTable;
