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';

export const HomeNoticeList = () => {
  
  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}` }
          id={ resultList[i]?.id }
          title={ resultList[i]?.title }
          category={ resultList[i]?.category }
          regDate={ resultList[i]?.regDate }
          isNew={ resultList[i]?.isNew }
        ></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>공지 & 최신정보</h3>
        <div className="notice-box">
          { (!!resultList && resultList.length > 0) && 
            getItems() 
          }
        </div>
      </div>
    </>
  );
};
