text: import React, {
    Suspense,
    useContext,
    useEffect,
    useRef,
    useState,
  } from "react";
  import Box from "@material-ui/core/Box";
  import makeStyles from "@material-ui/core/styles/makeStyles";
  import Toast from "Components/Toast";
  import useToast from "hooks/useToast";
  import PropTypes from "prop-types";
  import {
    APERO_ENGINEERS,
    APERO_ID,
    DEFAULT_STRINGS,
    noop,
    SERVER_URL,
  } from "utils/constants/common";
  import { TOAST_ERROR, TOAST_SUCCESS } from "utils/constants/ToastConstants";
  import { v4 as uuid } from "uuid";
  import EditorControls from "./EditorControls";
  import EditorLoader from "./EditorLoader";
  import axios from "axios";
  import {
    ColumnsContext,
    RowsContext,
    SaveQueryModalVisibleContext,
    CurrentQueryContext,
    ActiveTabIndexContext,
    TabDataContext,
    TabOrderContext,
  } from "context/AppContext";
  
  // Lazy loading Editor
  const LazyEditor = React.lazy(() => import("./LazyEditor"));
  
  /**
   * Material Ui recommend writing css styles in hook style  (css in js)
   * Can use Styled Components as well
   * It helps in making it easier to manage and make changes to the components
   * and prevent confliciting styles
   */
  const useStyles = makeStyles((theme) => ({
    editorStyles: {
      border: `1px solid ${theme.palette.divider}`,
      borderRight: "0",
    },
  }));
  
  function getStorageValue(key, defaultValue) {
    // getting stored value
    const saved = localStorage.getItem(key);
    const initial = JSON.parse(saved);
    return initial || defaultValue;
  }
  
  export const useLocalStorage = (key, defaultValue) => {
    const [value, setValue] = useState(() => {
      return getStorageValue(key, defaultValue);
    });
  
    useEffect(() => {
      // storing input name
      localStorage.setItem(key, JSON.stringify(value));
    }, [key, value]);
  
    return [value, setValue];
  };
  
  const QueryEditor = ({ onRunQuery = noop }) => {
    const classes = useStyles();
  
    const [columns, setColumns] = useContext(ColumnsContext);
    const [name, setName] = useLocalStorage("name", "");
    const [rows, setRows] = useContext(RowsContext);
    const [activeTabIndex, setActiveTabIndex] = useContext(ActiveTabIndexContext);
    const [tabData, setTabData] = useContext(TabDataContext);
    const [tabOrder, setTabOrder] = useContext(TabOrderContext);
    const [_, setSaveQueryModalVisible] = useContext(
      SaveQueryModalVisibleContext
    );
    const [currentQuery, setCurrentQuery] = useContext(CurrentQueryContext);
    const [query, setQuery] = useState(currentQuery);
  
    // const { currentQuery, handleQueryChange, editorTabs, updateEditorTabs } =
    //   useActiveQueryEditor();
    const { isToastVisible, showToast, toastType, toastMessage } = useToast();
  
    const handleRunQuery = async () => {
      if (!query) {
        showToast(TOAST_ERROR, "Please Enter Query");
        return;
      }
  
      const clientId = "6238b0e81d4d1dd35267ee52";
      const customerId = "1";
  
      const response = await axios.post(
        `${SERVER_URL}/query/${APERO_ID}/${APERO_ENGINEERS}/`,
        {
          query,
        }
      );
      const { data } = response;
      const columns = data.fields;
      const { rows } = data;
      setColumns(columns);
      setRows(rows);
      showToast(TOAST_SUCCESS, "Query Ran Successfully");
    };
  
    const handleShowSaveQueryModal = () => {
      setCurrentQuery(query);
      setSaveQueryModalVisible(true);
    };
  
    const handleQueryChange = (query) => {
      setQuery(query);
    };
  
    const handleSaveQueryToTab = () => {
      const activeTabId = tabOrder[activeTabIndex];
      setTabData((tabData) => {
        return {
          ...tabData,
          [activeTabId]: { ...tabData[activeTabId], query },
        };
      });
    };
  
    // when tab changes, change query
    useEffect(() => {
      setQuery(tabData[tabOrder[activeTabIndex]].query);
    }, [activeTabIndex]);
  
    return (
      <Box>
        <EditorControls
          handleSaveQueryToTab={handleSaveQueryToTab}
          onRunQuery={handleRunQuery}
          onSaveQuery={handleShowSaveQueryModal}
        />
        <Suspense fallback={<EditorLoader />}>
          <LazyEditor
            aria-label="query editor input"
            // TODO: MAKE CUSTOMIZABLE
            mode="mysql"
            theme="tomorrow"
            name={uuid()}
            fontSize={16}
            maxLines={14}
            minLines={14}
            width="100%"
            showPrintMargin={false}
            showGutter
            highlightActiveLine={false}
            placeholder={DEFAULT_STRINGS.QUERY_EDITOR_PLACEHOLDER}
            editorProps={{ $blockScrolling: true }}
            setOptions={{
              enableBasicAutocompletion: true,
              enableLiveAutocompletion: true,
              enableSnippets: true,
            }}
            value={query}
            onChange={handleQueryChange}
            className={classes.editorStyles}
            // showLineNumbers
          />
        </Suspense>
        <Toast show={isToastVisible} type={toastType} message={toastMessage} />
      </Box>
    );
  };
  
  export default QueryEditor;
  
  QueryEditor.propTypes = {
    onRunQuery: PropTypes.func.isRequired,
  };
  