import { PATHS } from '@/shared/constants/paths';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import {
  FooterProps,
  FooterItemActiveKey
} from '@/entities/common/model/types';
import { useEffect, useState } from 'react';
import { useAppBridge } from '@/hooks';
import { useTranslation } from 'react-i18next';

export const FooterNavigation = ({
  setMenuOn,
  footerCurrentPage,
  setFavoriteEdit
}: FooterProps) => {
  const { navigate } = useNavigate();
  const { t } = useTranslation();
  const [isFooterOn, setIsFooterOn] = useState<boolean>(true);

  const onClickToNavigate = (path?: string) => {
    if(!!path){
      navigate(path);
    }
  };
  const onClickToOpenMenu = () => {
    setFavoriteEdit(false);
    setMenuOn(true);
  };
  
  const buttonItems = [
    {
      activeIcon: IMAGE_ROOT + '/home-active.svg',
      inactiveIcon: IMAGE_ROOT + '/home.svg',
      path: PATHS.home,
      activeKey: FooterItemActiveKey.Home,
      title: t('footer.home')
    },
    {
      activeIcon: IMAGE_ROOT + '/chart-active.svg',
      inactiveIcon: IMAGE_ROOT + '/chart.svg',
      path: PATHS.transaction.allTransaction.list,
      activeKey: FooterItemActiveKey.Transaction,
      title: t('footer.transaction')
    },
    {
      activeIcon: IMAGE_ROOT + '/money-active.svg',
      inactiveIcon: IMAGE_ROOT + '/money.svg',
      path: PATHS.settlement.list,
      activeKey: FooterItemActiveKey.Settlement,
      title: t('footer.settlement')
    },
    {
      activeIcon: IMAGE_ROOT + '/users-active.svg',
      inactiveIcon: IMAGE_ROOT + '/users.svg',
      path: PATHS.account.user.manage,
      activeKey: FooterItemActiveKey.Account,
      title: t('footer.account')
    },
    {
      activeIcon: IMAGE_ROOT + '/more-active.svg',
      inactiveIcon: IMAGE_ROOT + '/more.svg',
      title: t('footer.more')
    },
  ];

  const getFooterButtonItems = () => {
    let rs = [];
    for(let i=0;i<buttonItems.length;i++){
      rs.push(
        <button
          key={ `footer-button-item-${i}` }
          className={ `tab-button ${((footerCurrentPage && footerCurrentPage === buttonItems[i]?.activeKey)? 'active': '')}` } 
          data-tab={ `tab-${i}` } 
          data-active-icon={ buttonItems[i]?.activeIcon } 
          data-inactive-icon={ buttonItems[i]?.inactiveIcon }
          onClick={ () => {
              if(!!buttonItems[i]?.path){
                onClickToNavigate(buttonItems[i]?.path);
              }
              else{
                onClickToOpenMenu();
              }
            }
          }
        >
          <div className="tab-icon">
            <img 
              className="tab-icon-img" 
              src={ (footerCurrentPage && footerCurrentPage === buttonItems[i]?.activeKey)? buttonItems[i]?.activeIcon: buttonItems[i]?.inactiveIcon } 
              alt={ buttonItems[i]?.title }
            />
          </div>
          <span className="tab-text">{ buttonItems[i]?.title }</span>
        </button>
      )
    }
    return rs;
  };

  useEffect(() => {
    const tabbar = document.querySelector('.bottom-tabbar') as HTMLElement;
    if (!tabbar) return;

    const TABBAR_HEIGHT = 70;
    const SAFE_AREA_BOTTOM = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--sab')) || 34;
    const TOTAL_HIDE_HEIGHT = TABBAR_HEIGHT + SAFE_AREA_BOTTOM;
    const SCROLL_THRESHOLD = 50;
    const SNAP_THRESHOLD = 0.5; // 50% 보이면 표시, 아니면 숨김
    const SCROLL_MULTIPLIER = 0.8; // 스크롤의 80%만큼 이동

    console.log('TABBAR_HEIGHT:', TABBAR_HEIGHT, 'SAFE_AREA_BOTTOM:', SAFE_AREA_BOTTOM, 'TOTAL_HIDE_HEIGHT:', TOTAL_HIDE_HEIGHT);

    let lastScrollY = 0;
    let currentTranslateY = 0; // 별도로 추적
    let isScrolling = false;
    let scrollTimeout: NodeJS.Timeout;
    let ticking = false;

    const handleScroll = () => {
      const currentScrollY = window.scrollY;
      const scrollDelta = currentScrollY - lastScrollY;

      if (!ticking) {
        window.requestAnimationFrame(() => {
          // 스크롤 시작
          if (!isScrolling) {
            isScrolling = true;
            tabbar.classList.remove('snapping');
          }

          // 스크롤 방향에 따라 translateY 조정
          // 스크롤 다운
          if (scrollDelta > 0) {
            currentTranslateY = Math.min(currentTranslateY + scrollDelta * SCROLL_MULTIPLIER, TOTAL_HIDE_HEIGHT);
          }
          // 스크롤 업
          else {
            currentTranslateY = Math.max(currentTranslateY + scrollDelta * SCROLL_MULTIPLIER, 0);
          }

          tabbar.style.transform = `translateY(${currentTranslateY}px)`;

          lastScrollY = currentScrollY;
          ticking = false;
        });

        ticking = true;
      }

      // 스크롤 중지 감지
      clearTimeout(scrollTimeout);
      scrollTimeout = setTimeout(() => {
        isScrolling = false;

        // 현재 위치 확인 후 snap
        const visibleRatio = 1 - (currentTranslateY / TOTAL_HIDE_HEIGHT);

        tabbar.classList.add('snapping');

        if (visibleRatio >= SNAP_THRESHOLD) {
          // 50% 이상 보이면 완전히 표시
          currentTranslateY = 0;
          tabbar.style.transform = 'translateY(0)';
        } else {
          // 50% 미만이면 완전히 숨김
          currentTranslateY = TOTAL_HIDE_HEIGHT;
          tabbar.style.transform = `translateY(${TOTAL_HIDE_HEIGHT}px)`;
        }
      }, 150);
    };

    window.addEventListener('scroll', handleScroll, { passive: true });

    return () => {
      window.removeEventListener('scroll', handleScroll);
      clearTimeout(scrollTimeout);
    };
  }, []);

  return (
    <>
      { isFooterOn &&
        <nav className="bottom-tabbar">
        { getFooterButtonItems() }
        </nav>
      }
    </>
  );
};
