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 { useFaqListMutation } from '@/entities/support/api/use-faq-list-mutation';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { FaqItem, FaqListParams, FaqListResponse, SearchCl } from '@/entities/support/model/types';
import { SupportFaqItem } from '@/entities/support/ui/faq-item';
import { 
	useSetHeaderTitle,
	useSetHeaderType,
	useSetFooterMode,
  useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';
import useIntersectionObserver from '@/widgets/intersection-observer';

export const FaqListPage = () => {
  const { navigate } = useNavigate();
  const { t } = useTranslation();

  const [onActionIntersect, setOnActionIntersect] = useState<boolean>(false);
  const [pageParam, setPageParam] = useState<DefaultRequestPagination>(DEFAULT_PAGE_PARAM);
  const [searchValue, setSearchValue] = useState<string>('');
  const [selectedCategory, setSelectedCategory] = useState<string>('');
  const [resultList, setResultList] = useState<Array<FaqItem>>([]);

  useSetHeaderTitle(t('support.faq.title'));
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(false);
  useSetOnBack(() => {
    navigate(PATHS.home);
  });

  const { mutateAsync: faqList } = useFaqListMutation();

  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: FaqListParams = {
      category: selectedCategory,
      searchCl: (!!searchValue)? SearchCl.HEAD: null,
      searchValue: searchValue,
      page: pageParam
    };
    if(type !== 'page' && listParams.page){
      listParams.page.cursor = null;
    }
    
    faqList(listParams).then((rs: FaqListResponse) => {
      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 onClickToAction = () => {
    // Remove focus from active element
    if (document.activeElement instanceof HTMLElement) {
      document.activeElement.blur();
    }
    callList();
  };

  const getFaqList = () => {
    let rs = [];
    for(let i=0;i<resultList.length;i++){
      rs.push(
        <SupportFaqItem
          key={ `key-support-faq-item-${i}` }
          cursorId={ resultList[i]?.cursorId }
          seq={ resultList[i]?.seq }
          category={ resultList[i]?.category }
          title={ resultList[i]?.title }
          contents={ resultList[i]?.contents }
        ></SupportFaqItem>
      )
    }
    return rs;
  };

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

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

  return (
    <>
      <main>
        <div className="tab-content">
          <div className="tab-pane sub active">
            <div className="faq-section pb-86">
              <div className="notice-controls">
                <div className="faq-search">
                  <span 
                    className="ic16 search" 
                    aria-hidden="true"
                    onClick={ () => onClickToAction() }
                  ></span>
                  <input
                    type="text"
                    placeholder={ t('support.faq.searchPlaceholder') }
                    value={ searchValue }
                    onChange={ (e: ChangeEvent<HTMLInputElement>) => setSearchValue(e.target.value) }
                    onKeyDown={ (e: React.KeyboardEvent<HTMLInputElement>) => {
                      if (e.key === 'Enter' && !e.nativeEvent.isComposing) {
                        onClickToAction();
                      }
                    }}
                  />
                </div>
                <div className="notice-filter">
                  <select
                    className="flex-1"
                    value={ selectedCategory }
                    onChange={ (e: ChangeEvent<HTMLSelectElement>) => setSelectedCategory(e.target.value) }
                  >
                    <option value="">{ t('support.faq.categories.all') }</option>
                    <option value="01">{ t('support.faq.categories.01') }</option>
                    <option value="02">{ t('support.faq.categories.02') }</option>
                    <option value="03">{ t('support.faq.categories.03') }</option>
                    <option value="04">{ t('support.faq.categories.04') }</option>
                    <option value="05">{ t('support.faq.categories.05') }</option>
                    <option value="06">{ t('support.faq.categories.06') }</option>
                    <option value="07">{ t('support.faq.categories.07') }</option>
                    <option value="99">{ t('support.faq.categories.99') }</option>                  </select>
                </div>
              </div>
              <div className="faq-list">
                { getFaqList() }
              </div>
              <div ref={ setTarget }></div>
            </div>
            <div className="apply-row">
              <button 
                className="btn-50 btn-blue flex-1"
                onClick={ () => onClickToNavigation() }
              >{t('support.faq.inquiryButton')}</button>
            </div>
          </div>
        </div>
      </main>
    </>
  );
};