import { useTranslation } from 'react-i18next';
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';
import { showAlert } from '@/widgets/show-alert';

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

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

    useSetHeaderTitle(t('additionalService.linkPayment.messagePreview'));
    useSetFooterMode(false);

    const getErrorMessage = (errorData: any, validationErrors: any, defaultMessage: string): string => {
        // validation 에러가 있으면 첫 번째 에러 메시지 반환
        if (validationErrors && typeof validationErrors === 'object') {
            const errorValues = Object.values(validationErrors);
            if (errorValues.length > 0 && errorValues[0]) {
                return errorValues[0] as string;
            }
        }
        return errorData?.message || defaultMessage;
    };

    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 = getErrorMessage(
                        rs.error,
                        rs.error?.details?.validationErrors,
                        t('additionalService.linkPayment.requestProcessingError')
                    );
                    snackBar(`[${t('common.failed')}] ${errorMessage}`);
                }
            })
            .catch((error) => {
                const errorData = error?.response?.data?.error;
                const errorMessage = getErrorMessage(
                    errorData,
                    errorData?.details?.validationErrors,
                    error?.message || t('additionalService.linkPayment.requestError')
                );

                if (errorData?.root !== "SystemErrorCode") {
                    snackBar(`[${t('common.failed')}] ${errorMessage}`);
                } else {
                    showAlert(`[${t('common.failed')}] ${errorMessage}`)
                }
            });
    };

    const onClickToBack = () => {
        navigate(PATHS.additionalService.linkPayment.request, {
            state: { formData, returnToStep: 2 }
        });
    };

    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={t('common.confirm')} />
                        </div>
                        <h1 className="preview-title">{t('additionalService.linkPayment.confirmSendMessage')}</h1>
                        <div className="preview-result">
                            <p className="preview-text">
                                {t('additionalService.linkPayment.customerGreeting', { buyerName: formData?.buyerName || '' })}<br />
                                {t('additionalService.linkPayment.paymentGuideMessage')}<br /><br />
                                <b>
                                    {t('additionalService.linkPayment.merchantName')} : 나이스페이먼츠 주식회사<br />
                                    {t('transaction.fields.productName')} : {formData?.goodsName || ''}<br />
                                    {t('transaction.fields.amount')} : {(formData?.amount || 0).toLocaleString()}{t('common.currencyUnit')}
                                </b>
                            </p>
                        </div>
                    </div>
                </div>

                <div className="apply-row two-button">
                    <button
                        className="btn-50 btn-darkgray flex-1"
                        onClick={() => onClickToBack()}
                    >{t('additionalService.linkPayment.previous')}</button>
                    <button
                        className="btn-50 btn-blue flex-3"
                        onClick={() => onClickToConfirm()}
                    >{t('additionalService.linkPay.paymentRequest')}</button>
                </div>
            </main>
        </>
    );
};