import React, { useState, useEffect, useCallback } from "react";
import PropTypes from "prop-types";
import TableChartIcon from "@mui/icons-material/TableChart";
import ViewListIcon from "@mui/icons-material/ViewList";
import { ToggleButtonGroup, ToggleButton } from "@mui/material";
import { Tooltip } from "@mui/material";
import { useTranslation } from "react-i18next";
import { ViewModes } from "../constants";

const ViewModeSelection = ({ initialMode, callback }) => {
  const [state, setState] = useState({
    mode: initialMode,
    manual: false
  });

  const { t } = useTranslation();

  const handleViewModeSelection = useCallback((event, mode) => {
    setState({ mode, manual: true });
  }, []);

  useEffect(() => {
    const mediaQuery = window.matchMedia("(max-width: 1100px)");

    function handleMatches(event) {
      if (state.manual === true) return;
      const mode = event.matches ? ViewModes.ACCORDION : ViewModes.TABLE;
      setState({ mode, manual: false });
    }

    handleMatches(mediaQuery);
    mediaQuery.addListener(handleMatches);

    return () => {
      mediaQuery.removeListener(handleMatches);
    };
  }, [state.manual]);

  useEffect(() => callback && callback(state.mode), [callback, state.mode]);

  return (
    <ToggleButtonGroup size="small" value={state.mode} exclusive onChange={handleViewModeSelection}>
      <ToggleButton value={ViewModes.TABLE} aria-label="table view mode" disabled={state.mode === ViewModes.TABLE}>
        <Tooltip title={t("ViewModes.Table")}>
          <TableChartIcon />
        </Tooltip>
      </ToggleButton>
      <ToggleButton
        value={ViewModes.ACCORDION}
        aria-label="accordion view mode"
        disabled={state.mode === ViewModes.ACCORDION}
      >
        <Tooltip title={t("ViewModes.List")}>
          <ViewListIcon />
        </Tooltip>
      </ToggleButton>
    </ToggleButtonGroup>
  );
};

ViewModeSelection.propTypes = {
  initialMode: PropTypes.oneOf([ViewModes.TABLE, ViewModes.ACCORDION]),
  callback: PropTypes.func
};

export default ViewModeSelection;
