import React, { useCallback, useEffect, useRef, useState } from "react";

import { useDispatch, useSelector } from "react-redux";

import { Spotlight } from "@enact/spotlight";

import {
  clearThemeMenuShelfInfo,
  getThemeMenuShelfInfo,
} from "../../actions/homeActions";
import { sendLogGNB, sendLogTotalRecommend } from "../../actions/logActions";
import { popPanel, updatePanel } from "../../actions/panelActions";
import CustomImage from "../../components/CustomImage/CustomImage";
import TBody from "../../components/TBody/TBody";
import TButton, { TYPES } from "../../components/TButton/TButton";
import THeader from "../../components/THeader/THeader";
import { removeDotAndColon } from "../../components/TItemCard/TItemCard";
import TPanel from "../../components/TPanel/TPanel";
import TVerticalPagenator from "../../components/TVerticalPagenator/TVerticalPagenator";
import {
  LOG_CONTEXT_NAME,
  LOG_MENU,
  LOG_MESSAGE_ID,
  panel_names,
} from "../../utils/Config";
import { $L } from "../../utils/helperMethods";
// import { SpotlightIds } from "../../utils/SpotlightIds";
import ThemeCurationContents from "./ThemeCurationContents/ThemeCurationContents";
import css from "./ThemeCurationPanel.module.less";

export default function ThemeCurationPanel({ panelInfo, spotlightId }) {
  const dispatch = useDispatch();

  const panels = useSelector((state) => state.panels.panels);

  const themeMenuShelfInfo = useSelector(
    (state) => state.home.themeMenuShelfInfoData
  );

  const [firstFocusableTarget, setFirstFocusableTarget] = useState();
  const [isInitialFocusOccurred, setIsInitialFocusOccurred] = useState(false);
  const [isInitialRendered, setIsInitialRendered] = useState(true);
  const [isReadyForInitialFocusTarget, setIsReadyForInitialFocusTarget] =
    useState(false);
  const [isTopButtonClicked, setIsTopButtonClicked] = useState(null);
  const [selectedCurationId, setSelectedCurationId] = useState("");
  const [panelType, setPanelType] = useState("");
  const [spotlightDisabled, setSpotlightDisabled] = useState(true);
  const [panelInfos, setPanelInfos] = useState();
  const [hasPanelInfo, setHasPanelInfo] = useState();
  const [previousPanelIsDetail, setPreviousPanelIsDetail] = useState();
  const [currentFocusedId, setCurrentFocusedId] = useState("");
  const cbChangePageRef = useRef(null);
  const focusedContainerIdRef = useRef(0);
  const prevShelfIndexRef = useRef(null);

  const timerRef = useRef(null);

  const { banrImgUrl, curationId, shelfInfos } = themeMenuShelfInfo || {};

  useEffect(() => {
    dispatch(sendLogGNB(LOG_MENU.THEME_PAGE));
  }, []);

  const handlePreviousButton = useCallback(
    () => () => {
      dispatch(popPanel());
    },
    [dispatch]
  );

  const getPanelInfo = useCallback(() => {
    if (panels) {
      for (let i = 0; i < panels.length; i++) {
        if (panels[i].name === panel_names.THEME_CURATION_PANEL) {
          setSelectedCurationId(panels[i].panelInfo.curationId);
          setPanelType(panels[i].name);
          setPanelInfos(panels[i].panelInfo);
        }
      }
    }

    if (panelInfos) {
      setHasPanelInfo(Object.keys(panelInfos).length > 0);
      setPreviousPanelIsDetail(Object.keys(panelInfos).length >= 5);
    }
  }, [panelInfos, panels]);

  useEffect(() => {
    getPanelInfo();

    if (panelType === panel_names.THEME_CURATION_PANEL) {
      dispatch(getThemeMenuShelfInfo({ curationId: selectedCurationId }));
    }
  }, [dispatch, panelType, selectedCurationId]);

  useEffect(() => {
    if (isInitialRendered) {
      if (previousPanelIsDetail) {
        return setIsInitialRendered(false);
      }
    }
  }, [isInitialRendered, previousPanelIsDetail]);

  useEffect(() => {
    if (themeMenuShelfInfo) {
      const prdtId = shelfInfos[0]?.shelfProductInfos[0]?.prdtId;

      setFirstFocusableTarget("spotlightId-" + removeDotAndColon(prdtId));
      setIsReadyForInitialFocusTarget(true);
    }
  }, [themeMenuShelfInfo, shelfInfos]);

  useEffect(() => {
    if (isReadyForInitialFocusTarget && !isInitialFocusOccurred) {
      let targetId;

      if (hasPanelInfo) {
        if (previousPanelIsDetail) {
          targetId = panelInfos?.targetId;
        }
        if (!previousPanelIsDetail) {
          targetId = firstFocusableTarget;
        }
      }

      setSpotlightDisabled(false);

      setTimeout(() => {
        const initialFocusTarget = document.querySelector(
          `[data-spotlight-id="${targetId}"]`
        );

        if (initialFocusTarget) {
          Spotlight.focus(initialFocusTarget);
          setIsInitialFocusOccurred(true);
        }
      });
    }
  }, [
    firstFocusableTarget,
    hasPanelInfo,
    isInitialFocusOccurred,
    isReadyForInitialFocusTarget,
    panelInfos,
    previousPanelIsDetail,
    themeMenuShelfInfo,
  ]);

  useEffect(() => {
    return () => {
      const lastFocusedTarget = Spotlight.getCurrent();

      if (lastFocusedTarget) {
        const exprOrd = parseInt(
          lastFocusedTarget.getAttribute("data-exposure-order")
        );
        const targetId = lastFocusedTarget.getAttribute("data-spotlight-id");

        dispatch(
          updatePanel({
            name: panel_names.THEME_CURATION_PANEL,
            panelInfo: {
              curationId,
              exprOrd,
              focusedContainerId: focusedContainerIdRef.current,
              targetId,
            },
          })
        );
      }

      clearTimeout(timerRef.current);
    };
  }, [dispatch, curationId]);

  useEffect(() => {
    dispatch(clearThemeMenuShelfInfo());
  }, [dispatch]);

  const handleTopButtonClick = useCallback(() => {
    if (cbChangePageRef.current) {
      cbChangePageRef.current(0, true, true);
    }

    if (!firstFocusableTarget) {
      return;
    }

    setIsTopButtonClicked(true);

    timerRef.current = setTimeout(() => {
      Spotlight.focus(firstFocusableTarget);
      setIsTopButtonClicked(false);
    }, 200);
  }, [firstFocusableTarget]);

  const onFocusedContainerId = useCallback((containerId) => {
    focusedContainerIdRef.current = containerId;
  }, []);

  useEffect(() => {
    const handleFocusChange = (spotlightId) => {
      if (spotlightId !== currentFocusedId) {
        setCurrentFocusedId(spotlightId);
        const shelfIndex = () => {
          const getFocusedContainerId = focusedContainerIdRef.current;
          if (!getFocusedContainerId) return;

          if (
            getFocusedContainerId === "themeCuration_verticalPagenator" ||
            getFocusedContainerId.includes("container-")
          ) {
            return 0;
          }
          if (getFocusedContainerId.includes("theme-info")) {
            return Number(getFocusedContainerId.replace("theme-info-", ""));
          }
          return;
        };
        const currentShelfIndex = shelfIndex();
        if (currentShelfIndex !== prevShelfIndexRef.current) {
          prevShelfIndexRef.current = currentShelfIndex;
          shelfInfos?.map((item, index) => {
            if (
              index === currentShelfIndex ||
              (index === 0 && currentShelfIndex === 0)
            ) {
              const params = {
                curationId: themeMenuShelfInfo?.curationId,
                curationTitle: themeMenuShelfInfo?.curationNm,
                shelfLocation: item.shelfExpsOrd,
                shelfId: item.shelfId,
                shelfTitle: item.shelfNm,
                contextName: LOG_CONTEXT_NAME.THEME_CURATION,
                messageId: LOG_MESSAGE_ID.SHELF,
              };
              dispatch(sendLogTotalRecommend(params));
            }
          });
        }
      }
    };

    const checkFocus = () => {
      const focusedElement = Spotlight.getCurrent();
      if (focusedElement) {
        const spotlightId = focusedElement.getAttribute("data-spotlight-id");
        handleFocusChange(spotlightId);
      }
    };

    const handleMouseOver = (e) => {
      const target = e.target.closest("[data-spotlight-id]");
      if (target) {
        const spotlightId = target.getAttribute("data-spotlight-id");
        handleFocusChange(spotlightId);
      }
    };

    const intervalId = setInterval(checkFocus, 100);
    document.addEventListener("mouseover", handleMouseOver);

    return () => {
      clearInterval(intervalId);
      document.removeEventListener("mouseover", handleMouseOver);
    };
  }, [currentFocusedId, shelfInfos, themeMenuShelfInfo]);

  return (
    <TPanel
      className={css.tPanel}
      isTabActivated={false}
      spotlightDisabled={spotlightDisabled}
      spotlightId={spotlightId}
    >
      {shelfInfos && (
        <TVerticalPagenator
          cbChangePageRef={cbChangePageRef}
          className={css.tVerticalPagenator}
          data-wheel-point
          defaultContainerId={panelInfo?.focusedContainerId}
          enableFocusAction={false}
          onFocusedContainerId={onFocusedContainerId}
          spotlightId={"themeCuration_verticalPagenator"}
          topMargin={36}
        >
          <figure className={css.banner}>
            <CustomImage alt="" src={banrImgUrl ?? ""} />
          </figure>

          <THeader
            className={css.tHeader}
            data-wheel-point
            onBackButton
            onClick={handlePreviousButton()}
            title={themeMenuShelfInfo?.curationNm}
          />

          <TBody className={css.tBody} scrollable={false}>
            {shelfInfos && (
              <>
                {shelfInfos.map(
                  ({ shelfNm, shelfProductInfos }, contentsIndex) => (
                    <ThemeCurationContents
                      contentsIndex={contentsIndex}
                      isTopButtonClicked={isTopButtonClicked}
                      key={"theme-info-" + contentsIndex}
                      shelfNm={shelfNm}
                      shelfProductInfos={shelfProductInfos}
                      shelfProductInfosLength={shelfProductInfos?.length}
                      spotlightId={"theme-info-" + contentsIndex}
                    />
                  )
                )}

                {shelfInfos.length > 1 && (
                  <TButton
                    onClick={handleTopButtonClick}
                    size={null}
                    type={TYPES.topButton}
                    ariaLabel="Move to Top"
                    data-wheel-point
                    spotlightId={"themeCuration_tButton"}
                  />
                )}
              </>
            )}
          </TBody>
        </TVerticalPagenator>
      )}
    </TPanel>
  );
}
