import moment from 'moment';
import { useCallback, useEffect, useState } from 'react';
import { useUserInfo } from '@/entities/user/lib/use-user-info';
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 { useStore } from '@/shared/model/store';
import { StorageKeys } from '@/shared/constants/local-storage';
import { setLocalStorage, getLocalStorage } from '@/shared/lib/web-view-bridge';
import { useAppBridge } from '@/hooks/useAppBridge';
import { HeaderType } from '@/entities/common/model/types';
import { 
	useSetHeaderTitle,
	useSetHeaderType,
	useSetFooterMode,
  useSetFooterCurrentPage,
  useSetFavoriteEdit,
  useSetMenuOn
} from '@/widgets/sub-layout/use-sub-layout';

export const HomePage = () => {
  const { callLogin } = useUserInfo();
  const { 
    isNativeEnvironment,
    openBiometricRegistrationPopup,
    requestToken,
    logout
  } = useAppBridge();
  useSetHeaderTitle('');
  useSetHeaderType(HeaderType.Home);
  useSetFooterMode(true);
  useSetFooterCurrentPage(FooterItemActiveKey.Home);
  //useSetFavoriteEdit(true);
  //useSetMenuOn(true);

  const today = moment().format('YYYYMMDD').toString();
  let bannerToday = getLocalStorage(StorageKeys.BottomBannerClose);
  
  const [bottomBannerOn, setBottomBannerOn] = useState<boolean>(false);
  const [authRegisterOn, setAuthRegisterOn] = useState<boolean>(false);
  const [loginSuccess, setLoginSuccess] = useState<boolean>(false);

  

  
  /*
  const userParmas = {
    id: 'thenaun12',
    password: 'answjddl1!'
  };
  */
  
  const handleRequestToken = useCallback(async () =>{
    console.log('handleRequestToken');
    alert('handleRequestToken');
    requestToken()
      .then((token) => {
        if (!token) {
          // 토큰이 null인 경우 로그아웃 처리
          console.error('Token is null, performing logout');
          useStore.getState().UserStore.resetUserInfo();
          setLoginSuccess(false);
          logout();
          return;
        }
        console.log('token', token);

				setLocalStorage(StorageKeys.Usrid, token.usrid);
        setLocalStorage(StorageKeys.TokenType, token.tokenType);
				setLocalStorage(StorageKeys.AccessToken, token.accessToken);
				setLocalStorage(StorageKeys.RefreshToken, token.refreshToken);
				setLocalStorage(StorageKeys.AccessTokenExpiresIn, token.accessTokenExpiresIn);
				setLocalStorage(StorageKeys.RefreshTokenExpiresIn, token.refreshTokenExpiresIn);
				setLocalStorage(StorageKeys.MenuGrants, token.menuGrants);

        useStore.getState().UserStore.setUserInfo({
          usrid: token.usrid,
          tokenType: token.tokenType,
          accessToken: token.accessToken,
          refreshToken: token.refreshToken,
          accessTokenExpiresIn: token.accessTokenExpiresIn,
          refreshTokenExpiresIn: token.refreshTokenExpiresIn,
          menuGrants: token.menuGrants,
        });

        setLoginSuccess(true);
      })
      .catch((error) => {
        // 토큰 요청 실패 시 로그아웃 처리
        console.error('Failed to request token:', error);
        useStore.getState().UserStore.resetUserInfo();
        setLoginSuccess(false);
        logout();
      });

  }, []);

  const userParmas = {
    id: 'nictest00',
    password: 'nictest00'
  };
  
  const handleLogin = useCallback(async () =>{
    //let appStart = getLocalStorage(StorageKeys.AppStart);
    //if(!!appStart){
    if(false){
      useStore.getState().UserStore.resetUserInfo();
      let tokenType = getLocalStorage(StorageKeys.TokenType);
      let accessToken = getLocalStorage(StorageKeys.AccessToken);
      let refreshToken = getLocalStorage(StorageKeys.RefreshToken);
      let accessTokenExpiresIn = getLocalStorage(StorageKeys.AccessTokenExpiresIn);
      let refreshTokenExpiresIn = getLocalStorage(StorageKeys.RefreshTokenExpiresIn);
      let menuGrants = getLocalStorage(StorageKeys.TokenType);
      // let usrid = getLocalStorage(StorageKeys.Usrid);
      
      useStore.getState().UserStore.setUserInfo({
        tokenType: tokenType,
        accessToken: accessToken,
        refreshToken: refreshToken,
        accessTokenExpiresIn: accessTokenExpiresIn,
        refreshTokenExpiresIn: refreshTokenExpiresIn,
        menuGrants: menuGrants,
        // usrid: usrid
      });
      setLoginSuccess(true);
    }
    else{
      callLogin(userParmas).then(() => {
        setLoginSuccess(true);
      });
    }
    
  }, []);

  const checkBottomBannerOpen = () => {
    console.log('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(() => {
    // handleRequestToken();
    if (isNativeEnvironment) {
      handleRequestToken();
    } else {
      handleLogin();
    }
    
    checkBottomBannerOpen();
    checkAuthRegisterOpen();

    
  }, []);
  
  const setBottomBannerEffect = (mode: boolean) => {
    setBottomBannerOn(mode);
    if(mode === false){
      if(authRegisterOn){
        setAuthRegisterOn(false);
        setTimeout(() => {
          setAuthRegisterOn(true);
        }, 500)
      }
    }
  };

  /*useLoginMutation
  const [userInfo] = useStore(
    useShallow((state) => [state.userSlice.userInfo]),
  );

  */
  // useRefreshUserInfo();
  return (
    <>
      <main>
        {/*<!-- 탭 컨텐츠 영역 -->*/}
        <div className="tab-content blue">
          <div className="tab-pane dashboard active">
            { loginSuccess && 
              <>
                <FavoriteWrapper
                  usingType='home'
                ></FavoriteWrapper>
                <DayStatusBox></DayStatusBox>
              </>
            }
          </div>
        </div>
      </main>
      <HomeBottomBanner 
        setBottomBannerOn={ setBottomBannerEffect }
        bottomBannerOn={ bottomBannerOn }
      ></HomeBottomBanner>
      { (!bottomBannerOn) &&
        <AuthRegister
          setAuthRegisterOn={ setAuthRegisterOn }
          authRegisterOn={ authRegisterOn }
        ></AuthRegister>
      }
    </>
  );
};
