import React, { useEffect, useState } from "react";
import { useUserContext } from "../Contexts/UserContext";

import supersetAPI from "../../services/superset";
import { MenuItem } from "../Layouts/MenuItem";

const SupersetDashboardList = () => {
  const [dashboardList, setDashboardList] = useState([])
  const { groups } = useUserContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();

  useEffect(() => {
    if (groups && token) {
      const internalEffect = async (token) => {
        const embeddedDashboards = await await supersetAPI.getEmbeddedDashboards(token)
        const submenus = embeddedDashboards.map((dashboard) => {
          return {
            label: dashboard.title,
            to: "/datascope/" + dashboard.embedded_id,
            roles: [],
          }
        })
        setDashboardList(submenus)
      }

      internalEffect(token)
    }
    return () => {
      setDashboardList([]);
    }
  }, [groups, token])

  return (
    <ul style={{ marginLeft: 50 }}>
      {dashboardList.map((subitem, index) => (
        <MenuItem key={`submenu-${index}`} item={subitem} />
      ))}
    </ul>
  )
}

export default SupersetDashboardList