import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";

import { getCustomDashboard } from "../../services/customDashboards";
import { useStatusContext } from "../Contexts/StatusContext";
import useStyles from "../useStyles";

const DashboardCustom = () => {
  const classes = useStyles();
  const [dashboard, setDashboard] = useState(null);
  const { setTitle, setSitePath } = useStatusContext();
  const { index } = useParams();

  useEffect(() => {
    const result = getCustomDashboard(parseInt(index));
    setDashboard(result);
    setTitle("Datascope");
    setSitePath([{ label: result.label}]);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [index]);

  if (!dashboard) return <div>Loading...</div>;
  if (dashboard.error) return <span className="error">{dashboard.error}</span>;
  if (dashboard.url) return <iframe className={classes.iframe} src={dashboard.url} title={dashboard.label}/>;
  if (dashboard.component) return dashboard.component;

  return <div>{dashboard.label} misconfigured</div>
};

export default DashboardCustom;