import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { ListDateGroup } from '../list-date-group';
import { AdditionalServiceCategory } from '../../model/types'
import { AccountHolderSearchListItem, AccountHolderSearchListProps } from '../../model/account-holder-search/types';
import { JSX } from 'react';

export const AccountHolderSearchList = ({
    listItems,
    mid,
    setTarget
}: AccountHolderSearchListProps) => {
    const { navigate } = useNavigate();

    const getListDateGroup = () => {
        let rs: JSX.Element[] = [];
        let date = '';
        let list: AccountHolderSearchListItem[] = [];
        for (let i = 0; i < listItems.length; i++) {
            // requestDate format: "20211018140420" (YYYYMMDDHHmmss)
            let requestDate = listItems[i]?.requestDate || '';
            let itemDate = requestDate.substring(0, 8);
            if (i === 0) {
                date = itemDate;
            }
            if (date !== itemDate) {
                // 날짜가 바뀌면 이전 리스트를 푸시 (날짜 업데이트 전에!)
                if (list.length > 0) {
                    rs.push(
                        <ListDateGroup
                            additionalServiceCategory={AdditionalServiceCategory.AccountHolderSearch}
                            mid={mid}
                            key={date + '-' + i}
                            date={date}
                            items={list as any}
                        ></ListDateGroup>
                    );
                }
                date = itemDate;  // 그 다음에 날짜 업데이트
                list = [];
            }
            list.push(listItems[i] as any);
        }
        if (list.length > 0) {
            rs.push(
                <ListDateGroup
                    additionalServiceCategory={AdditionalServiceCategory.AccountHolderSearch}
                    mid={mid}
                    key={date + '-last'}
                    date={date}
                    items={list as any}
                ></ListDateGroup>
            );
        }
        return rs;
    };

    const onClickToNavigate = () => {
        navigate(PATHS.additionalService.accountHolderSearch.request)
    };

    return (
        <>
            <section className="transaction-list">
                {getListDateGroup()}
                <div ref={setTarget}></div>
            </section>
            <div className="apply-row">
                <button
                    className="btn-50 btn-blue flex-1"
                    onClick={() => onClickToNavigate()}
                >조회 신청</button>
            </div>
        </>
    );
}