import { useEffect, useState } from 'react';
import { useNoticeListMutation } from '@/entities/support/api/use-notice-list-mutation';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { NoticeItem } from '@/entities/support/model/types';
import { HomeNoticeItem } from './home-notice-item';
import { useTranslation } from 'react-i18next';

export const HomeNoticeList = () => {
  const { t } = useTranslation();
  
  const [pageParam, setPageParam] = useState(DEFAULT_PAGE_PARAM);
  const [resultList, setResultList] = useState<Array<NoticeItem>>([]);

  const { mutateAsync: noticeList } = useNoticeListMutation();

  const getItems = () => {
    let rs = [];
    let maxCnt = (!!resultList && resultList.length < 4)? resultList.length: 4;
    for(let i=0;i<maxCnt;i++){
      rs.push(
        <HomeNoticeItem 
          key={ `key-home-notice-item-${i}` }
          seq={ resultList[i]?.seq }
          title={ resultList[i]?.title }
          informCl={ resultList[i]?.informCl }
          regDt={ resultList[i]?.regDt }
        ></HomeNoticeItem>
      );
    }
    return rs;
  };

  const callList = () => {
    let listParams = {
      category: 'ALL',
      searchKeyword: '',
      ...{page: pageParam}
    };
  
    noticeList(listParams).then((rs) => {
      setResultList(rs.content);
    });
  };

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

  return (
    <>
      <div className="notice-list">
        <h3>{t('home.noticesAndUpdates')}</h3>
        <div className="notice-box">
          { (!!resultList && resultList.length > 0) &&
            getItems()
          }
        </div>
      </div>
    </>
  );
};
