import { useStore } from '@/shared/model/store';
import { ChangeEvent, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { DefaultRequestPagination, HeaderType } from '@/entities/common/model/types';
import { useQnaListMutation } from '@/entities/support/api/use-qna-list-mutation';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { QnaItem, QnaListParams, QnaListResponse } from '@/entities/support/model/types';
import { SupportQnaItem } from '@/entities/support/ui/qna-item';
import useIntersectionObserver from '@/widgets/intersection-observer';
import { 
	useSetHeaderTitle,
	useSetHeaderType,
	useSetFooterMode,
  useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';

export const QnaListPage = () => {
  const { navigate } = useNavigate();
  const { t } = useTranslation();
  
  const midOptions = useStore.getState().UserStore.selectOptionsMids;
  const userMid = useStore.getState().UserStore.mid;
  let midItem = midOptions.filter((value, index) => {
    return value.value === userMid;
  });
  
  const [onActionIntersect, setOnActionIntersect] = useState<boolean>(false);
  const [mid, setMid] = useState<string>((midItem.length > 0)? userMid: '');
  const [pageParam, setPageParam] = useState<DefaultRequestPagination>(DEFAULT_PAGE_PARAM);
  const [statusCode, setStatusCode] = useState<string>(''); // 02, 03
  const [resultList, setResultList] = useState<Array<QnaItem>>([]);
 
  useSetHeaderTitle(t('support.qna.title'));
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(false);
  useSetOnBack(() => {
    navigate(PATHS.home);
  });

  const { mutateAsync: qnaList } = useQnaListMutation();

  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) => {
    setOnActionIntersect(false);
    let listParams: QnaListParams = {
      mid: mid,
      statusCode: statusCode,
      page: pageParam
    };
    if(type !== 'page'){
      if(listParams.page){
        listParams.page.cursor = null;
      }
    }
    
    qnaList(listParams).then((rs: QnaListResponse) => {
      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 getQnaList = () => {
    let rs = [];
    for(let i=0;i<resultList.length;i++){
      rs.push(
        <SupportQnaItem
          key={ `key-support-faq-item-${i}` }
          answer={ resultList[i]?.answer }
          answerDate={ resultList[i]?.answerDate }
          contents={ resultList[i]?.contents }
          corpName={ resultList[i]?.corpName }
          cursorId={ resultList[i]?.cursorId }
          requestDate={ resultList[i]?.requestDate }
          requestName={ resultList[i]?.requestName } 
          requestType={ resultList[i]?.requestType }
          sendEmail={ resultList[i]?.sendEmail }
          seq={ resultList[i]?.seq }
          statusCode={ resultList[i]?.statusCode }
          title={ resultList[i]?.title }
        ></SupportQnaItem>
      );
    }
    return rs;
  };

  const onClickToNavigation = () => {
    navigate(PATHS.support.qna.register);
  };

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

  return (
    <>
      <main>
        <div className="tab-content">
          <div className="tab-pane sub active">
            <div className="inq117 pb-86">
              <div className="inq-merchant">
                <div className="inq-title">{t('support.qna.merchant')}</div>
                <div className="notice-filter">
                  <select 
                    className="flex-1"
                    value={ mid } 
                    onChange={ (e: ChangeEvent<HTMLSelectElement>) => setMid(e.target.value) }
                  >
                  { 
                    midOptions.map((value, index) => (
                      <option
                        key={ value.value }
                        value={ value.value }
                      >{ value.name }</option>
                    )) 
                  }  
                  </select>
                </div>
              </div>
              <div className="notice-filter">
                <select
                  className="flex-1"
                  value={ statusCode }
                  onChange={(e: ChangeEvent<HTMLSelectElement>) => setStatusCode(e.target.value)}
                >
                  <option value="">{t('support.qna.statusCode.all')}</option>
                  <option value="02">{t('support.qna.statusCode.02')}</option>
                  <option value="03">{t('support.qna.statusCode.03')}</option>
                </select>
              </div>
              <div className="inq-list" >
                { getQnaList() }
              </div>
              <div ref={ setTarget }></div>
            </div>
            <div className="apply-row">
              <button 
                className="btn-50 btn-blue flex-1"
                onClick={ () => onClickToNavigation() }
              >{t('support.qna.inquiryButton')}</button>
            </div>
          </div>
        </div>
      </main>
      
    </>
  );
};