import moment from 'moment';
import { IMAGE_ROOT } from "@/shared/constants/common";
import { useState, useEffect } from "react";
import { LinkPaymentWaitSendFilter } from "./filter/link-payment-pending-send-filter";
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { PATHS } from "@/shared/constants/paths";
import { LinkPaymentWaitList } from "./link-payment-wait-list";
import { AdditionalServiceCategory, LinkPaymentWaitListItem, LinkPaymentSearchType, LinkPaymentSendingStatus, LinkPaymentSendMethod, SortByKeys } from "../../model/types";
import { SortOptionsBox } from '../sort-options-box';
import { useExtensionLinkPayWaitListMutation } from '../../api/link-payment/use-extension-link-pay-wait-list-mutation';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { useExtensionLinkPayWaitDownloadExcelMutation } from '../../api/link-payment/use-extension-link-pay-wait-download-excel-mutation';
const sendingStatusBtnGrouup = [
    { name: '전체', value: LinkPaymentSendingStatus.ALL },
    { name: '발송요청', value: LinkPaymentSendingStatus.SEND_REQUEST },
    { name: '발송취소', value: LinkPaymentSendingStatus.SEND_CANCEL }
]

export const LinkPaymentWaitSendWrap = () => {
    const { navigate } = useNavigate();

    const [sortBy, setSortBy] = useState<SortByKeys>(SortByKeys.New);
    const [filterOn, setFilterOn] = useState<boolean>(false);
    const [mid, setMid] = useState<string>('nictest001m');
    const [searchType, setSearchType] = useState<LinkPaymentSearchType>(LinkPaymentSearchType.ALL)
    const [searchKeyword, setSearchKeyword] = useState<string>('');
    const [startDate, setStartDate] = useState(moment().format('YYYY-MM-DD'));
    const [endDate, setEndDate] = useState(moment().format('YYYY-MM-DD'));
    const [sendMethod, setSendMethod] = useState<LinkPaymentSendMethod>(LinkPaymentSendMethod.ALL);
    const [sendingStatus, setSendingStatus] = useState<LinkPaymentSendingStatus>(LinkPaymentSendingStatus.ALL);
    const [listItems, setListItems] = useState({});
    const [pageParam, setPageParam] = useState(DEFAULT_PAGE_PARAM);

    const { mutateAsync: pendingSendList } = useExtensionLinkPayWaitListMutation();
    const { mutateAsync: downloadExcel } = useExtensionLinkPayWaitDownloadExcelMutation();

    const onClickToOpenFilter = () => {
        setFilterOn(!filterOn);
    };
    const onClickToNavigate = () => {
        navigate(PATHS.additionalService.linkPayment.request)
    }

    const callList = (option?: {
        sortBy?: string,
        val?: string
    }) => {
        pageParam.sortBy = (option?.sortBy) ? option.sortBy : sortBy;
        setPageParam(pageParam);

        let listParams = {
            mid: mid,
            searchCl: searchType === LinkPaymentSearchType.ALL ? '' : searchType,
            searchValue: searchKeyword,
            fromDate: startDate,
            toDate: endDate,
            sendStatus: sendingStatus === LinkPaymentSendingStatus.ALL ? '' : sendingStatus, // 추후 삭제 필요
            sendMethod: sendMethod === LinkPaymentSendMethod.ALL ? '' : sendMethod,
            processStatus: sendingStatus === LinkPaymentSendingStatus.ALL ? '' : sendingStatus,
            page: pageParam
        }

        pendingSendList(listParams).then((rs) => {
            setListItems(assembleData(rs.content))
        })
    };

    const assembleData = (content: Array<LinkPaymentWaitListItem>) => {
        let data: any = {};
        if (content && content.length > 0) {
            for (let i = 0; i < content?.length; i++) {
                let scheduledSendDate = content[i]?.scheduledSendDate?.substring(0, 8);
                let groupDate = moment(scheduledSendDate).format('YYYYMMDD');
                if (!!groupDate && !data.hasOwnProperty(groupDate)) {
                    data[groupDate] = [];
                }
                if (!!groupDate && data.hasOwnProperty(groupDate)) {
                    data[groupDate].push(content[i]);
                }
            }
        }
        console.log('Data : ', data)
        return data;
    };

    const onClickToDownloadExcel = () => {
        downloadExcel({
            mid: mid,
            searchCl: searchType === LinkPaymentSearchType.ALL ? '' : searchType,
            searchValue: searchKeyword,
            fromDate: startDate,
            toDate: endDate,
            sendStatus: sendingStatus === LinkPaymentSendingStatus.ALL ? '' : sendingStatus, // 추후 삭제 필요
            sendMethod: sendMethod === LinkPaymentSendMethod.ALL ? '' : sendMethod,
            processStatus: sendingStatus === LinkPaymentSendingStatus.ALL ? '' : sendingStatus,
        }).then((rs) => {
            console.log('Excel Dowload Status : ' + rs.status)
        });
    };

    const onClickToSort = (sort: SortByKeys) => {
        setSortBy(sort);
    };

    const onClickSendingStatus = (val: LinkPaymentSendingStatus) => {
        setSendingStatus(val);
    };

    useEffect(() => {
        callList();
    }, []);
    return (
        <>
            <section className="summary-section pt-30">
                <div className="credit-controls">
                    <div>
                        <input
                            className="credit-period"
                            type="text"
                            value={moment(startDate).format('YYYY.MM.DD') + '-' + moment(endDate).format('YYYY.MM.DD')}
                            readOnly={true}
                        />
                        <button
                            className="filter-btn">
                            <img
                                src={IMAGE_ROOT + '/ico_setting.svg'}
                                alt="검색옵션"
                                onClick={() => onClickToOpenFilter()}
                            />
                        </button>
                    </div>
                    <button
                        className="download-btn"
                        aria-label="다운로드"
                    >
                        <img
                            src={IMAGE_ROOT + '/ico_download.svg'}
                            alt="다운로드"
                            onClick={() => onClickToDownloadExcel()}
                        />
                    </button>
                </div>
            </section>

            <div className="filter-section">
                <SortOptionsBox
                    sortBy={sortBy}
                    onClickToSort={onClickToSort}
                ></SortOptionsBox>
                <div className="excrow">
                    <div className="full-menu-keywords no-padding">
                        {
                            sendingStatusBtnGrouup.map((value, index) => (
                                <span
                                    key={`key-service-code=${index}`}
                                    className={`keyword-tag ${(sendingStatus === value.value) ? 'active' : ''}`}
                                    onClick={() => onClickSendingStatus(value.value)}
                                >{value.name}</span>
                            ))
                        }
                    </div>
                </div>
            </div>

            <LinkPaymentWaitList
                listItems={listItems}
                additionalServiceCategory={AdditionalServiceCategory.LinkPaymentWait}
            ></LinkPaymentWaitList>
            <div className="apply-row">
                <button
                    className="btn-50 btn-blue flex-1"
                    onClick={() => onClickToNavigate()}
                >결제 신청</button>
            </div>
            <LinkPaymentWaitSendFilter
                filterOn={filterOn}
                setFilterOn={setFilterOn}
                mid={mid}
                searchType={searchType}
                searchKeyword={searchKeyword}
                startDate={startDate}
                endDate={endDate}
                sendMethod={sendMethod}
                sendingStatus={sendingStatus}
                setMid={setMid}
                setSearchType={setSearchType}
                setSearchKeyword={setSearchKeyword}
                setStartDate={setStartDate}
                setEndDate={setEndDate}
                setSendMethod={setSendMethod}
                setSendingStatus={setSendingStatus}
            ></LinkPaymentWaitSendFilter>
        </>
    )
}