'use client'

import React, { useEffect, useState } from 'react';
import { Modal, Result } from 'antd';
import { CloseOutlined } from '@ant-design/icons';
import { useSearchParams, useRouter } from 'next/navigation';
import { Stripe } from 'stripe';
import { getStripePaymentStatus } from '../../actions/stripe';
import { sessionPaymentConfirm } from '../../actions/sessions';
import { getStorageValue } from '../../hooks/useLocalStorage';
import { AUTH_TOKEN_KEY } from '../../constants/common';
import { Session, SessionState } from '../../types/sessions';
import { i18nText } from '../../i18nKeys';

export const ScheduleModalResult = ({ locale }: { locale: string }) => {
    const searchParams = useSearchParams();
    const [paymentStatus, setPaymentStatus] = useState<Stripe.PaymentIntent.Status | undefined>();
    const [session, setSession] = useState<Session | undefined>();
    const [error, setError] = useState<any>();
    const router = useRouter();

    useEffect(() => {
        setError(undefined);
        const payment_intent = searchParams.get('payment_intent') || false;
        if (payment_intent) {
            getStripePaymentStatus(payment_intent)
                .then((result) => {
                    setPaymentStatus(result?.status);
                    if (result?.status === 'succeeded' && result?.metadata?.sessionId) {
                        const jwt = getStorageValue(AUTH_TOKEN_KEY, '');
                        sessionPaymentConfirm(locale, jwt, +result.metadata.sessionId)
                            .then((session) => {
                                setSession(session);
                            })
                            .catch((err: any) => {
                                setError(err);
                            });
                    }
                })
                .catch((err: any) => {
                    setError(err);
                })
        }
    }, [searchParams]);

    const onClose = () => {
        const { origin, pathname } = window?.location || {};

        router.push(`${origin}${pathname}`);
        setPaymentStatus(undefined);
        setSession(undefined);
    };

    return (
        <Modal
            className="b-modal"
            open={paymentStatus === 'succeeded' && session?.state === SessionState.PAID}
            title={undefined}
            onOk={undefined}
            onCancel={onClose}
            footer={false}
            width={498}
            closeIcon={<CloseOutlined style={{ fontSize: 20, color: '#000' }}/>}
        >
            <div className="b-schedule-payment-result">
                <Result
                    status="success"
                    title={i18nText('successPayment', locale)}
                />
            </div>
        </Modal>
    );
}