import moment from 'moment';
import { useEffect, useState } from 'react';
import { FavoriteWrapper } from '@/entities/home/ui/favorite-wrapper';
import { DayStatusBox } from '@/entities/home/ui/day-status-box';
import { HomeBottomBanner } from '@/entities/home/ui/home-bottom-banner';
import { AuthRegister } from '@/entities/home/ui/auth-reguster';
import { FooterItemActiveKey } from '@/entities/common/model/types';
import { StorageKeys } from '@/shared/constants/local-storage';
import { getLocalStorage } from '@/shared/lib/web-view-bridge';
import { useAppBridge } from '@/hooks/useAppBridge';
import { HeaderType } from '@/entities/common/model/types';
import { 
	useSetHeaderTitle,
	useSetHeaderType,
	useSetFooterMode,
  useSetFooterCurrentPage
} from '@/widgets/sub-layout/use-sub-layout';
import { useStore } from '@/shared/model/store';
import { UserFavorite } from '@/entities/user/model/types';
import { useHomeBannerListMutation } from '@/entities/home/api/use-home-banner-list-mutation';
import { BannerList, BannerType, HomeBannerListParams, HomeBannerListResponse } from '@/entities/home/model/types';
import { IMAGE_ROOT } from '@/shared/constants/common';

export let homeReloadKey = 1;
export const setHomeReloadKey = () => {
  homeReloadKey++;
};

export const HomePage = () => {
  const { openBiometricRegistrationPopup } = useAppBridge();
  const { mutateAsync: homeBannerList } = useHomeBannerListMutation();
  
  useSetHeaderTitle('');
  useSetHeaderType(HeaderType.Home);
  useSetFooterMode(true);
  useSetFooterCurrentPage(FooterItemActiveKey.Home);
  
  const today = moment().format('YYYYMMDD').toString();
  let bannerToday = getLocalStorage(StorageKeys.BottomBannerClose);
  
  const [bottomBannerOn, setBottomBannerOn] = useState<boolean>(false);
  const [authRegisterOn, setAuthRegisterOn] = useState<boolean>(false);
  const [favoriteItems, setFavoriteItems] = useState<Array<UserFavorite>>([]);  
  const [bannerList, setBannerList] = useState<Array<BannerList>>([]);

  const callHomeBannerList = () => {
    let params: HomeBannerListParams = {
      bannerType: BannerType.BOTTOM
    };

    homeBannerList(params).then((rs: HomeBannerListResponse) => {
      console.log(rs);
      if(rs.bannerList && rs.bannerList.length > 0){
        setBannerList(rs.bannerList);
      }
      else{
        setBannerList([]);
      }
    }).finally(() => {
      /*
      let items = [
        {title: '배너 이미지1', imageUrl: IMAGE_ROOT + '/sample_banner_0.png',  linkUrl: 'http://www.google.com', order: 3},
        {title: '배너 이미지2', imageUrl: IMAGE_ROOT + '/home-banner01.png', linkUrl: 'http://www.naver.com', order: 1},
        {title: '배너 이미지3', imageUrl: IMAGE_ROOT + '/home-banner01.png', linkUrl: 'http://www.daum.net', order: 2},
      ];
      items.sort((a, b) => a.order - b.order);
      setBannerList(items);
      */
    });
  };
  

  const checkBottomBannerOpen = () => {
    if(!!bannerToday){
      bannerToday = bannerToday.toString();
    }
    let sw = (today !== bannerToday);
    setBottomBannerOn(sw);
  };
  const checkAuthRegisterOpen = () => {
    openBiometricRegistrationPopup().then((isOpen) => {
      if(isOpen){
        setAuthRegisterOn(true);
      }
    }).catch((e) => {
      console.log('catch', e); 
      
    }).finally(() => {
      console.log('finally');
       setAuthRegisterOn(true);
    });
  };

  
    
  useEffect(() => {
    let firstAccess = useStore.getState().UserStore.firstAccess;
    checkBottomBannerOpen();
    
    if(!!firstAccess){
      checkAuthRegisterOpen();
    }
    else{
      useStore.getState().UserStore.setFirstAccess(false);
    }
    
    let userFavorite = useStore.getState().UserStore.userFavorite;
    setFavoriteItems(userFavorite);
    callHomeBannerList();
   
  }, []);
  
  const setBottomBannerEffect = (mode: boolean) => {
    setBottomBannerOn(mode);
    if(mode === false){
      if(authRegisterOn){
        setAuthRegisterOn(false);
        setTimeout(() => {
          setAuthRegisterOn(true);
        }, 500)
      }
    }
  };
  
  return (
    <>
      <main className="home-main">
        {/*<!-- 탭 컨텐츠 영역 -->*/}
        <div className="tab-content blue">
          <div className="tab-pane dashboard active">
            <FavoriteWrapper
              usingType='home'
              key={ homeReloadKey }
            ></FavoriteWrapper>
            <DayStatusBox></DayStatusBox>
          </div>
        </div>
      </main>
      { !!bannerList && bannerList.length > 0 &&
        <HomeBottomBanner 
          setBottomBannerOn={ setBottomBannerEffect }
          bottomBannerOn={ bottomBannerOn }
          bannerList={ bannerList }
        ></HomeBottomBanner>
      }
      { (!bottomBannerOn) && 
        <AuthRegister
          setAuthRegisterOn={ setAuthRegisterOn }
          authRegisterOn={ authRegisterOn }
        ></AuthRegister>
      }
    </>
  );
};
