import { useEffect, useState } from 'react';
import { useNoticeListMutation } from '@/entities/support/api/use-notice-list-mutation';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constants';
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.length < 5)? resultList.length: 5;
    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) => {
      console.log(rs)
      setResultList(rs.content);
    });
  };

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

  return (
    <>
      <div className="notice-list">
        <h3>공지 & 최신정보</h3>
        <div className="notice-box">
          { getItems() }
        </div>
      </div>
    </>
  );
};
