import { IMAGE_ROOT } from '@/shared/constants/common';
import { AlarmItem  } from './alarm-item';
import { AlarmLinkOptions, AlarmListContent, AppAlarmListParams, AppAlarmListResponse, MERCHANT_ADMIN_APP } from '../model/types';
import { useEffect, useState } from 'react';
import { useAppAlarmListMutation } from '../api/use-app-alarm-list-mutation';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { useTranslation } from 'react-i18next';
import { useNavigate } from '@/shared/lib/hooks';
import useIntersectionObserver from '@/widgets/intersection-observer';
import { useStore } from '@/shared/model/store';
import { DefaultRequestPagination } from '@/entities/common/model/types';
import { AlarmRoutes } from './alarm-routes';

export interface AlarmListProps {
  appNotificationCategory: string;
};

export const AlarmList = ({
  appNotificationCategory
}: AlarmListProps) => {
  const { navigate } = useNavigate();
  const { t } = useTranslation();
  const userInfo = useStore.getState().UserStore.userInfo;
  
  const [onActionIntersect, setOnActionIntersect] = useState<boolean>(false);
  const [pageParam, setPageParam] = useState<DefaultRequestPagination>(DEFAULT_PAGE_PARAM);
  const [appCl, setAppCl] = useState<MERCHANT_ADMIN_APP>(MERCHANT_ADMIN_APP.MERCHANT_ADMIN_APP)
  const [resultList, setResultList] = useState<Array<AlarmListContent>>([]);
  const [alarmRoutesOn, setAlarmRoutesOn] = useState<boolean>(false);
  const [alarmOptions, setAlarmOptions] = useState<AlarmLinkOptions>();

  const { mutateAsync: appAlarmList } = useAppAlarmListMutation();

  const onIntersect: IntersectionObserverCallback = (entries: Array<IntersectionObserverEntry>) => {
    entries.forEach((entry: IntersectionObserverEntry) => {
      if(entry.isIntersecting){
        if(onActionIntersect && !!pageParam.cursor){
          setOnActionIntersect(false);
          callList('page');
        } 
      }
    });
  };

  const { setTarget } = useIntersectionObserver({ 
    threshold: 1, 
    onIntersect 
  });

  const callList = (type?: string) => {
    if(userInfo.usrid){
      let params: AppAlarmListParams = {
        usrid: userInfo.usrid,
        appCl: appCl,
        appNotificationCategory: appNotificationCategory,
        page: pageParam
      };

      if(type !== 'page' && params.page){
        params.page.cursor = null;
      }

      appAlarmList(params).then((rs: AppAlarmListResponse) => {
        if(rs){
          if(type === 'page'){
            setResultList([
              ...resultList,
              ...rs.content
            ]);
          }
          else{
            setResultList(rs.content);
          }
          if(rs.hasNext 
            && rs.nextCursor !== pageParam.cursor
            && rs.content.length === DEFAULT_PAGE_PARAM.size
          ){
            setPageParam({
              ...pageParam,
              ...{ cursor: rs.nextCursor }
            });
          }
          else{
            setPageParam({
              ...pageParam,
              ...{ cursor: null }
            });
          }
          setOnActionIntersect(
            !!rs.hasNext 
            && rs.nextCursor !== pageParam.cursor 
            && rs.content.length === DEFAULT_PAGE_PARAM.size
          );
        }
      });
    }
    
  };
  const getAlarmItems = () => {
    let rs = [];
    for(let i=0;i<resultList.length;i++){
      rs.push(
        <AlarmItem
          key={ 'alarm_key_' + resultList[i]?.appNotificationSequence }
          appNotificationSequence={ resultList[i]?.appNotificationSequence }
          appNotificationCategory={ resultList[i]?.appNotificationCategory }
          notificationReceivedDate={ resultList[i]?.notificationReceivedDate }
          appNotificationTitle={ resultList[i]?.appNotificationTitle }
          appNotificationContent={ resultList[i]?.appNotificationContent }
          appNotificationLink={ resultList[i]?.appNotificationLink }
          setAlarmRoutesOn={ setAlarmRoutesOn }
          setAlarmOptions={ setAlarmOptions }
        ></AlarmItem>
      );
    }
    return rs;
  };

  useEffect(() => {
    callList();
  }, [appNotificationCategory]);

  useEffect(() => {
    if(!!alarmRoutesOn){
      console.log(alarmOptions)
    }
  }, [alarmRoutesOn, alarmOptions]);
  
  return (
    <>
      <div className="notice-box sub">
      { getAlarmItems() }
      </div>
      <div ref={ setTarget }></div>
      <div className="notice-alert">{t('alarm.retentionNotice')}</div>
      { alarmRoutesOn &&
        <AlarmRoutes
          options={ alarmOptions }
        ></AlarmRoutes>
      }
    </>
  );
};