import { HeaderType } from '@/entities/common/model/types';
import { useSetFooterMode, useSetHeaderTitle, useSetHeaderType } from '@/widgets/sub-layout/use-sub-layout';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { useLocation } from 'react-router';
import { IMAGE_ROOT } from "@/shared/constants/common";
import { PATHS } from '@/shared/constants/paths';
import { useExtensionLinkPayRequestMutation } from '@/entities/additional-service/api/link-payment/use-extension-link-pay-request-mutation';
import { ExtensionLinkPayRequestParams, ExtensionLinkPayRequestResponse, LinkPaymentFormData } from '@/entities/additional-service/model/link-pay/types';
import { snackBar } from '@/shared/lib';

export const LinkPaymentApplyConfirmPage = () => {
    const { navigate } = useNavigate();
    const location = useLocation();

    const formData: LinkPaymentFormData = location.state?.formData;
    const { mutateAsync: linkPayRequest } = useExtensionLinkPayRequestMutation();

    useSetHeaderTitle('메시지 미리보기');
    useSetHeaderType(HeaderType.LeftArrow);
    useSetFooterMode(false);

    const onClickToConfirm = () => {
        if (!formData) {
            console.error('Form data is missing');
            return;
        }

        const requestParams: ExtensionLinkPayRequestParams = {
            mid: formData.mid,
            sendMethod: formData.sendMethod,
            goodsName: formData.goodsName,
            amount: formData.amount,
            moid: formData.moid,
            paymentLimitDate: formData.paymentLimitDate.replace(/\./g, ''),
            buyerName: formData.buyerName,
            ...(formData.sendMethod === 'EMAIL' && {
                email: formData.email
            }),
            ...((formData.sendMethod === 'SMS' || formData.sendMethod === 'KAKAO') && {
                phoneNumber: formData.phoneNumber,
            }),
            isIdentity: formData.isIdentity,
            ...(formData.isIdentity && {
                identityType: formData.identityType,
                identityValue: formData.identityValue,
            }),
            language: formData.language,
            linkContentType: formData.linkContentType
        };
        linkPayRequest(requestParams)
            .then((rs: ExtensionLinkPayRequestResponse) => {
                if (rs.status) {
                    navigate(PATHS.additionalService.linkPayment.confirmSuccess);
                } else {
                    // 일반 에러 메시지
                    const errorMessage = rs.error?.message || '요청을 처리할 수 없습니다.';
                    snackBar(`[실패] ${errorMessage}`);
                }
            })
            .catch((error) => {
                // 네트워크 에러 등 예외 상황
                const errorMessage = error?.response?.data?.error?.message ||
                    error?.message ||
                    '요청 중 오류가 발생했습니다';
                snackBar(`[실패] ${errorMessage}`);
            });
    };

    const onClickToBack = () => {
        navigate(-1);
    };

    return (
        <>
            <main className="pop">
                <div className="sub-wrap">
                    <div className="preview-body">
                        <div className="attention-icon" aria-hidden="true">
                            <img src={IMAGE_ROOT + '/ico_alert.svg'} alt="주의" />
                        </div>
                        <h1 className="preview-title">발송 메시지를<br />최종 확인하세요</h1>
                        <div className="preview-result">
                            <p className="preview-text">
                                {formData.buyerName}  고객님, 안녕하세요?<br />
                                나이스페이먼츠 주식회사에서 <br />
                                결제하실 내역 안내드립니다.<br />
                                아래 URL로 접속하시면 상세 내역 확인과 결제 진행이 가능합니다.<br /><br />
                                !$&#123;pay_url&#125;<br /><br />
                                <b>
                                    가맹점 상호 : 나이스페이먼츠 주식회사<br />
                                    상품명 : {formData.goodsName}<br />
                                    금액 : {formData.amount.toLocaleString()}원
                                </b>
                            </p>
                        </div>
                    </div>
                </div>

                <div className="apply-row two-button">
                    <button
                        className="btn-50 btn-darkgray flex-1"
                        onClick={() => onClickToBack()}
                    >이전</button>
                    <button
                        className="btn-50 btn-blue flex-3"
                        onClick={() => onClickToConfirm()}
                    >결제 신청</button>
                </div>
            </main>
        </>
    );
};