import React, { useEffect } from "react";

import Spotlight from "@enact/spotlight";

import TPanel from "../../components/TPanel/TPanel";
import useScrollTo from "../../hooks/useScrollTo";
import { LOG_MENU } from "../../utils/Config";
import { SpotlightIds } from "../../utils/SpotlightIds";
import css from "./MyPagePanel.module.less";
import Favorites from "./MyPageSub/Favorites/Favorites";
import MyInfo from "./MyPageSub/MyInfo/MyInfo";
import MyOrders from "./MyPageSub/MyOrders/MyOrders";
import RecentlyViewed from "./MyPageSub/RecentlyViewed/RecentlyViewed";
import Reminders from "./MyPageSub/Reminders/Reminders";
import Support from "./MyPageSub/Support/Support";
import TermsOfService from "./MyPageSub/TermsOfService/TermsOfService";
import { useDispatch } from "react-redux";
import { sendLogGNB } from "../../actions/logActions";

export default function MyPagePanel({ panelInfo, isOnTop, spotlightId }) {
  const dispatch = useDispatch();
  const { menuNm, menuOrd, menuId } = panelInfo || {};
  const { getScrollTo, scrollTop } = useScrollTo();

  const myPageComponents = {
    30800: MyInfo,
    30900: MyOrders,
    30300: RecentlyViewed,
    30200: Favorites,
    30400: Reminders,
    30500: Support,
    30600: TermsOfService,
  };

  const SelectedComponent = menuId && myPageComponents[menuId];

  useEffect(() => {
    const node = document.querySelector(`[id="${SpotlightIds.TBODY}"]`);
    if (node) {
      Spotlight.focus(node);
    }
  }, [panelInfo]);

  useEffect(() => {
    if (panelInfo?.menuNm) {
      dispatch(sendLogGNB(LOG_MENU.MY_PAGE + "/" + panelInfo.menuNm));
    }
  }, [panelInfo?.menuNm]);

  return (
    <TPanel className={css.tPanel} spotlightId={spotlightId}>
      {SelectedComponent && (
        <SelectedComponent
          scrollTop={scrollTop}
          title={menuNm}
          tab={menuOrd}
          panelInfo={panelInfo}
          isOnTop={isOnTop}
          cbScrollTo={getScrollTo}
        />
      )}
    </TPanel>
  );
}
