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

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

import platform from "@enact/core/platform";
import Spotlight from "@enact/spotlight";

// 테스트용 - TODO: 메인 홈 화면에 나와야 하는 이미지들 추가 후 preloadImages에 추가
import testImage from "../../../assets/img-banner-myinfo-login@3x.png";
import { changeAppStatus } from "../../actions/commonActions";
import { pushPanel } from "../../actions/panelActions";
import PreloadImage from "../../components/PreloadImage/PreloadImage";
import TabLayout from "../../components/TabLayout/TabLayout";
import * as Config from "../../utils/Config";
import CartPanel from "../CartPanel/CartPanel";
import CategoryPanel from "../CategoryPanel/CategoryPanel";
import DebugPanel from "../DebugPanel/DebugPanel";
import ErrorPanel from "../ErrorPanel/ErrorPanel";
import FeaturedBrandsPanel from "../FeaturedBrandsPanel/FeaturedBrandsPanel";
import HomePanel from "../HomePanel/HomePanel";
import HotPicksPanel from "../HotPicksPanel/HotPicksPanel";
import IntroPanel from "../IntroPanel/IntroPanel";
import LoadingPanel from "../LoadingPanel/LoadingPanel";
import MyPagePanel from "../MyPagePanel/MyPagePanel";
import OnSalePanel from "../OnSalePanel/OnSalePanel";
import SearchPanel from "../SearchPanel/SearchPanel";
import TrendingNowPanel from "../TrendingNowPanel/TrendingNowPanel";
import css from "./MainView.module.less";

const preloadImages = [testImage];

const panelMap = {
  [Config.panel_names.INTRO_PANEL]: IntroPanel,
  [Config.panel_names.HOME_PANEL]: HomePanel,
  [Config.panel_names.MY_PAGE_PANEL]: MyPagePanel,
  [Config.panel_names.CATEGORY_PANEL]: CategoryPanel,
  [Config.panel_names.SEARCH_PANEL]: SearchPanel,
  [Config.panel_names.ON_SALE_PANEL]: OnSalePanel,
  [Config.panel_names.TRENDING_NOW_PANEL]: TrendingNowPanel,
  [Config.panel_names.HOT_PICKS_PANEL]: HotPicksPanel,
  [Config.panel_names.FEATURED_BRANDS_PANEL]: FeaturedBrandsPanel,
  [Config.panel_names.CART_PANEL]: CartPanel,
  [Config.panel_names.ERROR_PANEL]: ErrorPanel,
  [Config.panel_names.DEBUG_PANEL]: DebugPanel,
};

export default function MainView() {
  const dispatch = useDispatch();
  const mainIndex = useSelector((state) => state.appData.mainIndex);
  const panels = useSelector((state) => state.panels.panels);
  const { showLoadingPanel } = useSelector((state) => state.common.appStatus);

  const [tabActivated, setTabActivated] = useState(false);
  const [isTermAgreed, setIsTermAgreed] = useState(false); // TODO: 약관 동의 체크 api 연동

  const isOnTop = useMemo(() => {
    return !mainIndex && panels.length <= 0;
  }, [mainIndex, panels.length]);

  const onPreImageLoadComplete = useCallback(() => {
    console.log('MainView onPreImageLoadComplete');
    // dispatch(changeAppStatus({ showLoadingPanel: { show: false } }));
  }, [dispatch]);

  const renderTopPanel = useCallback(() => {
    if (panels && panels.length > 0) {
      const panel = panels[panels.length - 1];
      const Component = panelMap[panel.name];

      return (
        <Component
          panelInfo={panel.panelInfo}
          spotlightId={panel.name}
          isTabActivated={tabActivated}
        />
      );
    } else {
      return null;
    }
  }, [panels]);

  const onTabActivated = useCallback((activated) => {
    setTabActivated(activated);
  }, []);

  const topPanelName = useMemo(() => {
    if (panels && panels.length > 0) {
      return panels[panels.length - 1].name;
    }

    return null;
  }, [panels]);

  useEffect(() => {
    if (panels && panels.length > 0) {
      const panel = panels[panels.length - 1];

      Spotlight.focus(panel.name);
    }
  }, [panels]);

  useEffect(() => {
    if (!showLoadingPanel.show) {
      if (isTermAgreed) {
      } else {
        dispatch(
          pushPanel({ name: Config.panel_names.INTRO_PANEL, panelInfo: {} })
        );
      }
    }
  }, [showLoadingPanel.show, isTermAgreed, dispatch]);

  const cursorStateChange = useCallback(
    (ev) => {
      dispatch(
        changeAppStatus({
          cursorVisible: ev.visibility || ev.detail.visibility,
        })
      );
    },
    [dispatch]
  );

  useEffect(() => {
    document.addEventListener("cursorStateChange", cursorStateChange, false);
    if (platform.platformName !== "webos") {
      //for debug
      dispatch(changeAppStatus({ cursorVisible: !platform.touchscreen }));
    } else {
      dispatch(
        changeAppStatus({
          cursorVisible: window.cursorEvent && window.cursorEvent.visibility,
        })
      );
    }
    return () => {
      document.removeEventListener("cursorStateChange", cursorStateChange);
    };
  }, []);

  return (
    <>
      <PreloadImage
        preloadImages={preloadImages}
        onLoadComplete={onPreImageLoadComplete}
      />
      {isOnTop ? (
        <HomePanel />
      ) : (
        <div
          className={classNames(
            css.mainlayout,
            showLoadingPanel.show ? css.transparent : null
          )}
        >
          {renderTopPanel()}
        </div>
      )}
      <TabLayout topPanelName={topPanelName} onTabActivated={onTabActivated} />
      <LoadingPanel showLoadingPanel={showLoadingPanel} />
    </>
  );
}
