text: import Drawer from "@material-ui/core/Drawer";
  import List from "@material-ui/core/List";
  import makeStyles from "@material-ui/core/styles/makeStyles";
  import Typography from "@material-ui/core/Typography";
  import clsx from "clsx";
  import EmptyState from "Components/EmptyState";
  import SidebarListItem from "Components/SideBar/SidebarListItem";
  import { v4 as uuid } from "uuid";
  import { format } from "sql-formatter";
  import {
    APERO_ENGINEERS,
    APERO_ID,
    DEFAULT_STRINGS,
    DRAWER_WIDTH,
    SERVER_URL,
  } from "utils/constants/common";
  import Proptypes from "prop-types";
  import { docco } from "react-syntax-highlighter/dist/esm/styles/hljs";
  import SyntaxHighlighter from "react-syntax-highlighter";
  import ChevronRightIcon from "@material-ui/icons/ChevronRight";
  import { useContext, useEffect } from "react";
  import axios from "axios";
  import {
    SchemaContext,
    SelectedSidebarIndexContext,
    HistoryContext,
    SavedQueriesContext,
    ActiveTabIndexContext,
    TabOrderContext,
    TabDataContext,
  } from "context/AppContext";
  import { Button, ListItem } from "@material-ui/core";
  
  // SideBar Styles
  const useStyles = makeStyles((theme) => ({
    drawerPaper: {
      [theme.breakpoints.up("sm")]: {
        position: "relative",
      },
      whiteSpace: "nowrap",
      height: "100%",
      width: DRAWER_WIDTH,
      transition: theme.transitions.create("width", {
        easing: theme.transitions.easing.sharp,
        duration: theme.transitions.duration.short,
      }),
    },
    drawerPaperClose: {
      overflowX: "hidden",
      transition: theme.transitions.create("width", {
        easing: theme.transitions.easing.sharp,
        duration: theme.transitions.duration.short,
      }),
      width: 0,
    },
  }));
  
  // SideBar Component
  const SideBar = ({ showDrawer = true, items = [] }) => {
    const classes = useStyles();
    const [schema, setSchema] = useContext(SchemaContext);
    const [selectedSidebarIndex, setSelectedSidebarIndex] = useContext(
      SelectedSidebarIndexContext
    );
    const [history, setHistory] = useContext(HistoryContext);
    const [savedQueries, setSavedQueries] = useContext(SavedQueriesContext);
    const [tabData, setTabData] = useContext(TabDataContext);
    const [tabOrder, setTabOrder] = useContext(TabOrderContext);
    const [activeTabIndex, setActiveTabIndex] = useContext(ActiveTabIndexContext);
  
    const selectSavedQuery = (item) => {
      // TODO: save current tab query
  
      const newTabId = `editor_tab_${uuid()}`;
      const newTab = {
        name: item?.name || `Untitled Query`,
        id: newTabId,
        value: newTabId,
        canDelete: true,
        isActive: true,
        query: item?.queryString,
      };
      const newTabOrder = [...tabOrder, newTabId];
      setTabOrder(newTabOrder);
      setTabData({ ...tabData, [newTabId]: newTab });
      setActiveTabIndex(newTabOrder.length - 1);
    };
  
    useEffect(() => {
      async function getSchema() {
        const clientId = "6238b0e81d4d1dd35267ee52";
        const customerId = "1";
  
        const response = await axios.get(
          `${SERVER_URL}/schema/${APERO_ID}/${APERO_ENGINEERS}/`
        );
  
        setSchema(response.data);
      }
      async function getHistory() {
        const clientId = "6238b0e81d4d1dd35267ee52";
        const customerId = "1";
  
        const response = await axios.get(
          `${SERVER_URL}/history/${APERO_ID}/${APERO_ENGINEERS}/`
        );
  
        setHistory(response.data);
      }
      async function getSavedQueries() {
        const clientId = "6238b0e81d4d1dd35267ee52";
        const customerId = "1";
  
        const response = await axios.get(
          `${SERVER_URL}/saved/${APERO_ID}/${APERO_ENGINEERS}/`
        );
  
        setSavedQueries(response.data);
      }
      if (selectedSidebarIndex === 0) {
        getSchema();
        return;
      }
      if (selectedSidebarIndex === 1) {
        getHistory();
        return;
      }
      if (selectedSidebarIndex === 2) {
        getSavedQueries();
        return;
      }
    }, [selectedSidebarIndex]);
  
    return (
      <>
        <Drawer
          variant="permanent"
          classes={{
            paper: clsx(
              classes.drawerPaper,
              !showDrawer && classes.drawerPaperClose
            ),
          }}
          open={showDrawer}
        >
          {selectedSidebarIndex === 0 && schema.length === 0 ? (
            <EmptyState
              title={DEFAULT_STRINGS.NO_TABLES_EXIST}
              titleVariant="h6"
              subtitle={DEFAULT_STRINGS.IMPORT_NEW_DATA_MESSAGE}
            />
          ) : selectedSidebarIndex === 0 ? (
            <List style={{ paddingTop: 56 }}>
              {schema.map((item, index) => (
                <SidebarListItem
                  key={`${item.name}-${index}-table-metadata`}
                  listItem={item}
                />
              ))}
            </List>
          ) : null}
          {selectedSidebarIndex === 1 && schema.length === 0 ? (
            <EmptyState
              title={DEFAULT_STRINGS.NO_TABLES_EXIST}
              titleVariant="h6"
              subtitle={DEFAULT_STRINGS.IMPORT_NEW_DATA_MESSAGE}
            />
          ) : selectedSidebarIndex === 1 ? (
            <List style={{ paddingTop: 56 }}>
              {history.map((item, index) => (
                <HistoryListItem
                  key={`${item._id}-${index}-table-metadata`}
                  item={item}
                  selectSavedQuery={selectSavedQuery}
                />
              ))}
            </List>
          ) : null}
          {selectedSidebarIndex === 2 && savedQueries.length === 0 ? (
            <EmptyState
              title={DEFAULT_STRINGS.NO_TABLES_EXIST}
              titleVariant="h6"
              subtitle={DEFAULT_STRINGS.IMPORT_NEW_DATA_MESSAGE}
            />
          ) : selectedSidebarIndex === 2 ? (
            <List style={{ paddingTop: 56 }}>
              {savedQueries.map((item, index) => (
                <SavedQueryListItem
                  key={`${item._id}-${index}-table-metadata`}
                  item={item}
                  selectSavedQuery={selectSavedQuery}
                />
              ))}
            </List>
          ) : null}
          <div
            style={{
              display: "flex",
              flexDirection: "row",
              alignItems: "center",
              // justifyContent: "space-between",
              paddingLeft: 13,
              paddingRight: 25,
              height: 56,
              zIndex: 1000,
              background: "white",
              // paddingTop: 16,
              // paddingBottom: 8,
              borderBottom: "1px solid #F0F0F0",
              borderRight: "1px solid #F0F0F0",
              position: "fixed",
              top: 0,
              left: 0,
              width: 360,
            }}
          >
            <SidebarSectionButton
              name="Schema"
              index={0}
              selectedSidebarIndex={selectedSidebarIndex}
              setSelectedSidebarIndex={setSelectedSidebarIndex}
            />
            <SidebarSectionButton
              name="History"
              index={1}
              selectedSidebarIndex={selectedSidebarIndex}
              setSelectedSidebarIndex={setSelectedSidebarIndex}
            />
            <SidebarSectionButton
              name="Saved"
              index={2}
              selectedSidebarIndex={selectedSidebarIndex}
              setSelectedSidebarIndex={setSelectedSidebarIndex}
            />
          </div>
        </Drawer>
      </>
    );
  };
  
  function SavedQueryListItem({ item, selectSavedQuery }) {
    return (
      <ListItem
        button
        onClick={() => selectSavedQuery(item)}
        style={{
          display: "flex",
          flexDirection: "column",
          alignItems: "flex-start",
          paddingLeft: 20,
          paddingRight: 20,
          borderBottomWidth: 1,
          borderBottomColor: "#E0E0E0",
          borderBottomStyle: "solid",
          paddingTop: 16,
          paddingBottom: 10,
        }}
      >
        {/* add name of saved query */}
        <Row style={{ marginBottom: -7, marginTop: 6, width: "100%" }}>
          <div>
            <Typography
              style={{
                fontSize: 16,
                color: "#595959",
                fontWeight: "500",
                marginTop: 4,
              }}
            >
              {item.name}
            </Typography>
          </div>
          <ChevronRightIcon htmlColor="#595959" />
        </Row>
        <Typography
          style={{
            fontSize: 14,
            color: "#595959",
            marginTop: 8,
          }}
        >
          {new Date(item.createdAt).toDateString()}
        </Typography>
        {item?.queryString ? (
          <div style={{ width: "100%" }}>
            <SyntaxHighlighter language="sql" style={docco}>
              {format(item.queryString)}
            </SyntaxHighlighter>
          </div>
        ) : null}
      </ListItem>
    );
  }
  
  function HistoryListItem({ item, selectSavedQuery }) {
    // lmao
    if (!item.createdAt) {
      return null;
    }
    return (
      <ListItem
        button
        onClick={() => selectSavedQuery(item)}
        style={{
          display: "flex",
          flexDirection: "column",
          alignItems: "flex-start",
          paddingLeft: 20,
          paddingRight: 20,
          borderBottomWidth: 1,
          borderBottomColor: "#E0E0E0",
          borderBottomStyle: "solid",
          paddingTop: 16,
          paddingBottom: 10,
        }}
      >
        <Row style={{ marginBottom: -7, marginTop: 6, width: "100%" }}>
          <Typography
            style={{
              fontSize: 14,
              color: "#595959",
            }}
          >
            {new Date(item.createdAt).toDateString()}
          </Typography>
          <ChevronRightIcon htmlColor="#595959" />
        </Row>
        {item?.queryString ? (
          <div style={{ width: "100%" }}>
            <SyntaxHighlighter language="sql" style={docco}>
              {format(item.queryString)}
            </SyntaxHighlighter>
          </div>
        ) : null}
      </ListItem>
    );
  }
  
  function Row({ children, style }) {
    return (
      <div
        style={{
          display: "flex",
          flexDirection: "row",
          alignItems: "center",
          justifyContent: "space-between",
          ...style,
        }}
      >
        {children}
      </div>
    );
  }
  
  function SidebarSectionButton({
    name,
    index,
    selectedSidebarIndex,
    setSelectedSidebarIndex,
  }) {
    const setSelected = () => {
      setSelectedSidebarIndex(index);
    };
  
    if (selectedSidebarIndex === index) {
      return (
        <Button
          style={{
            fontSize: 16,
            fontWeight: "600",
            paddingLeft: 12,
            paddingRight: 12,
            color: "#7A6EFF",
          }}
        >
          {name}
        </Button>
      );
    }
    return (
      <Button
        style={{
          fontSize: 16,
          fontWeight: "400",
          paddingLeft: 12,
          paddingRight: 12,
        }}
        onClick={setSelected}
      >
        {name}
      </Button>
    );
  }
  
  export default SideBar;
  
  SideBar.propTypes = {
    items: Proptypes.array,
    showDrawer: Proptypes.bool.isRequired,
  };
  