import moment from 'moment';
import { IMAGE_ROOT } from "@/shared/constants/common";
import { useState, useEffect } from "react";
import { LinkPaymentHistoryFilter } from "./filter/link-payment-history-filter";
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { PATHS } from "@/shared/constants/paths";
import { LinkPaymentHistoryList } from "./link-payment-history-list";
import { SortOptionsBox } from "../sort-options-box";
import { AdditionalServiceCategory, LinkPaymentSendMethod, LinkPaymentHistoryListItem, LinkPaymentTransactionStatus, ProcessResult, SortByKeys } from "../../model/types";
import { LinkPaymentSearchType, } from "../../model/types";
import { useExtensionLinkPayHistoryListMutation } from '../../api/link-payment/use-extension-link-pay-history-list-mutation';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { useExtensionLinkPayHistoryDownloadExcelMutation } from '../../api/link-payment/use-extension-link-pay-history-download-excel-mutation';

const processResultBtnGroup = [
    { name: '전체', value: ProcessResult.ALL },
    { name: '성공', value: ProcessResult.SUCCESS },
    { name: '실패', value: ProcessResult.FAIL }
]

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

    const [filterOn, setFilterOn] = useState<boolean>(false);
    const [sortBy, setSortBy] = useState<SortByKeys>(SortByKeys.New);
    const [listItems, setListItems] = useState({});
    const [pageParam, setPageParam] = useState(DEFAULT_PAGE_PARAM);
    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 [transactionStatus, setTransactionStatus] = useState<LinkPaymentTransactionStatus>(LinkPaymentTransactionStatus.ALL)
    const [processResult, setProcessResult] = useState<ProcessResult>(ProcessResult.ALL)
    const [sendMethod, setSendMethod] = useState<LinkPaymentSendMethod>(LinkPaymentSendMethod.ALL)

    const { mutateAsync: linkPayHistoryList } = useExtensionLinkPayHistoryListMutation();
    const { mutateAsync: downloadExcel } = useExtensionLinkPayHistoryDownloadExcelMutation();

    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,
            paymentMethod: 'st', // 추후 변경 필요 빼야함
            fromDate: startDate,
            toDate: endDate,
            paymentStatus: transactionStatus === LinkPaymentTransactionStatus.ALL ? '' : transactionStatus,
            sendStatus: processResult === ProcessResult.ALL ? '' : processResult,
            sendMethod: sendMethod === LinkPaymentSendMethod.ALL ? '' : sendMethod,
            page: pageParam
        }

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

    const assembleData = (content: Array<LinkPaymentHistoryListItem>) => {
        let data: any = {};
        if (content && content.length > 0) {
            for (let i = 0; i < content?.length; i++) {
                let sendDate = content[i]?.sendDate?.substring(0, 8);
                let groupDate = moment(sendDate).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,
            paymentMethod: 'st', // 추후 변경 필요 빼야함
            fromDate: startDate,
            toDate: endDate,
            paymentStatus: transactionStatus === LinkPaymentTransactionStatus.ALL ? '' : transactionStatus,
            sendStatus: processResult === ProcessResult.ALL ? '' : processResult,
            sendMethod: sendMethod === LinkPaymentSendMethod.ALL ? '' : sendMethod,
        }).then((rs) => {
            console.log('Excel Dowload Status : ' + rs.status)
        });
    };

    const onClickProcessResult = (val: ProcessResult) => {
        setProcessResult(val);
    }

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

    const onClickToOpenFilter = () => {
        setFilterOn(!filterOn);
    };

    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">
                        {
                            processResultBtnGroup.map((value, index) => (
                                <span
                                    key={`key-service-code=${index}`}
                                    className={`keyword-tag ${(processResult === value.value) ? 'active' : ''}`}
                                    onClick={() => onClickProcessResult(value.value)}
                                >{value.name}</span>
                            ))
                        }
                    </div>
                </div>
            </div>

            <LinkPaymentHistoryList
                listItems={listItems}
                additionalServiceCategory={AdditionalServiceCategory.LinkPaymentHistory}
            ></LinkPaymentHistoryList>
            <div className="apply-row">
                <button
                    className="btn-50 btn-blue flex-1"
                    onClick={() => onClickToNavigate()}
                >결제 신청</button>
            </div>
            <LinkPaymentHistoryFilter
                filterOn={filterOn}
                setFilterOn={setFilterOn}
                mid={mid}
                searchType={searchType}
                searchKeyword={searchKeyword}
                startDate={startDate}
                endDate={endDate}
                transactionStatus={transactionStatus}
                processResult={processResult}
                sendMethod={sendMethod}
                setMid={setMid}
                setSearchType={setSearchType}
                setSearchKeyword={setSearchKeyword}
                setStartDate={setStartDate}
                setEndDate={setEndDate}
                setTransactionStatus={setTransactionStatus}
                setProcessResult={setProcessResult}
                setSendMethod={setSendMethod}
            ></LinkPaymentHistoryFilter>
        </>
    )
}