import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { Menu } from '@/shared/ui/menu';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { PATHS } from '@/shared/constants/paths';
import {
  HeaderType,
  HeaderNavigationProps
} from '@/entities/common/model/types';
import { useStore } from '@/shared/model/store';
import { ChangeEvent, useEffect, useState } from 'react';
import { AppAlarmUnreadCountParams, AppAlarmUnreadCountResponse, MERCHANT_ADMIN_APP } from '@/entities/alarm/model/types';
import { useAppAlarmUnreadCountMutation } from '@/entities/alarm/api/use-app-alarm-unread-count-mutation';
import { appBridge } from '@/utils/appBridge';

export const HeaderNavigation = ({ 
  onBack, 
  headerTitle, 
  menuOn,
  headerType, 
  setMenuOn,
  favoriteEdit,
  loginSuccess,
  mid,
  setMid
}: HeaderNavigationProps) => {
  const { mutateAsync: appAlarmUnreadCount } = useAppAlarmUnreadCountMutation();
  
  let [selectOptions, setSelectOptions] = useState<Array<Record<string, string>>>([]);
  const [unreadCount, setUnreadCount] = useState<number>(0);

  const {
    navigate,
    navigateBack
  } = useNavigate();
  
  const handleBack = () => {
    if(onBack){
      onBack();
    }
    else{
      navigateBack();
    }
  };
  const handleClose = () => {
    if(onBack){
      onBack();
    }
    else{
      navigateBack();
    }
  };
  const onClickToGoToAlarm = () => {
    navigate(PATHS.alarm.list);
  };
  const onChangeToMid = (e: ChangeEvent<HTMLSelectElement>) => {
    let value = e.target.value;
    useStore.getState().UserStore.setMid(value);
    setMid(value);
  };

  const callAlarmCount = () => {
    const userInfo = useStore.getState().UserStore.userInfo;
    if(userInfo.usrid){
      let params: AppAlarmUnreadCountParams = {
        usrid: userInfo.usrid,
        appCl: MERCHANT_ADMIN_APP.MERCHANT_ADMIN_APP
      };
      appAlarmUnreadCount(params).then((rs: AppAlarmUnreadCountResponse) => {
        setUnreadCount(rs.unreadCount);
        // 네이티브 앱에 알림 카운트 업데이트
        if(appBridge.isNativeEnvironment()){
          appBridge.updateAlarmCount(rs.unreadCount).catch((error) => {
            console.error('Failed to update alarm count:', error);
          });
        }
      });
    }
  };
  useEffect(() => {
    if(headerType === HeaderType.Home){
      callAlarmCount();
    }
  }, [headerType]);
  useEffect(() => {
    let mids = useStore.getState().UserStore.selectOptionsMids;
    setSelectOptions(mids);
  }, [loginSuccess]);
  
  return (
    <>
      {
        (headerType === HeaderType.Home
          || headerType === HeaderType.Alim 
          || headerType === HeaderType.LeftArrow
        ) &&
        <Menu 
          menuOn={ menuOn }
          setMenuOn={ setMenuOn }
          favoriteEdit={ favoriteEdit }
        ></Menu>
      }
      { 
        (headerType !== HeaderType.NoHeader) &&
        <header className="header">
        {
          // 홈에서만 적용
          (headerType === HeaderType.Home) &&
          <div className="header-content">
            <div className="header-left">
              <h1 className="app-title blind">나이스가맹점관리자</h1>
                <div className="input-wrapper">
                  <select 
                    className="heading-select"
                    onChange={ onChangeToMid }
                    value={ mid }
                  >
                  { selectOptions && selectOptions.length > 0 && 
                    selectOptions.map((value, index) => (
                      <option 
                        key={ value.value }
                        value={ value.value }
                      >{ value.name }</option>
                    ))
                  }
                  </select>
                </div>
            </div>
            <div className="header-right">
              <button 
                className="header-btn notification-btn"
                onClick={ () => onClickToGoToAlarm() }
              >
                <span className="notification-icon"></span>
                { (unreadCount > 0) &&
                  <span className="notification-badge"></span>
                }
              </button>
              {
              /*
              <button className="header-btn profile-btn">
                <span className="profile-icon">👤</span>
              </button>
              */
              }
            </div>
          </div>
        }
        {
          (headerType === HeaderType.Alim) &&
          <div className="header-content sub">
            <div className="header-center">{ headerTitle }</div>
            <div className="header-right">
              <button 
                className="header-btn notification-btn"
                onClick={ () => onClickToGoToAlarm() }
              >
                  <span className="notification-icon"></span>
                  <span className="notification-badge"></span>
              </button>
            </div>
          </div>
        }
        {
          (headerType === HeaderType.LeftArrow) && 
          <div className="header-content">
            <div className="header-left">
              <button className="header-btn">
                <img 
                  src={ IMAGE_ROOT + '/ico_back.svg' }
                  alt="뒤로가기"
                  onClick={ () => handleBack() }
                />
              </button>
            </div>
            <div className="header-center">{ headerTitle }</div>
          </div>
        }
        {
          (headerType === HeaderType.RightClose) && 
          <div className="header-content">
            <div className="header-center">{ headerTitle }</div>
            <div className="header-right">
              <button className="header-btn">
                <img 
                  src={ IMAGE_ROOT + '/ico_close.svg' }
                  alt="닫기"
                  onClick={ () => handleClose() }
                />
              </button>
            </div>
          </div>
        }
        </header>
      }
    </>
  );
};
