'use client';

import { Suspense, useState, useEffect, useRef } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import api from '@/shared/api/axios';

type PageStatus = 'loading' | 'redirecting' | 'checking' | 'success' | 'error';

function PayContent() {
    const router = useRouter();
    const searchParams = useSearchParams();
    const [status, setStatus] = useState<PageStatus>('loading');
    const [errorMsg, setErrorMsg] = useState('');
    const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);

    useEffect(() => {
        const outTradeNo = searchParams.get('out_trade_no');
        if (outTradeNo) {
            setStatus('checking');
            startPolling(outTradeNo);
            return;
        }

        const token = sessionStorage.getItem('payment_token');
        if (!token) {
            router.replace('/login');
            return;
        }
        createOrder(token);

        return () => {
            if (pollRef.current) clearInterval(pollRef.current);
        };
    }, []);

    const createOrder = async (token: string) => {
        try {
            const { data } = await api.post('/api/payment/create-order', { payment_token: token });
            const { pay_url } = data.data;
            setStatus('redirecting');
            window.location.href = pay_url;
        } catch (err: any) {
            setStatus('error');
            setErrorMsg(err.response?.data?.message || '创建订单失败，请重新登录');
        }
    };

    const startPolling = (tradeNo: string) => {
        checkStatus(tradeNo);
        pollRef.current = setInterval(() => checkStatus(tradeNo), 3000);
    };

    const checkStatus = async (tradeNo: string) => {
        try {
            const { data } = await api.get(`/api/payment/status/${tradeNo}`);
            if (data.data.status === 'paid') {
                if (pollRef.current) clearInterval(pollRef.current);
                setStatus('success');
                sessionStorage.removeItem('payment_token');
                setTimeout(() => router.replace('/login'), 3000);
            }
        } catch {
            // ignore polling errors
        }
    };

    return (
        <div className="w-full max-w-md p-8 bg-white/10 backdrop-blur-lg rounded-2xl shadow-2xl border border-white/20">
            {(status === 'loading' || status === 'redirecting') && (
                <div className="text-center">
                    <div className="mb-6">
                        <svg className="animate-spin h-12 w-12 mx-auto text-purple-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                    </div>
                    <p className="text-gray-300">
                        {status === 'loading' ? '正在创建订单...' : '正在跳转到支付宝...'}
                    </p>
                </div>
            )}

            {status === 'checking' && (
                <div className="text-center">
                    <h1 className="text-2xl font-bold text-white mb-6">支付确认中</h1>
                    <div className="flex items-center justify-center gap-2 text-purple-300 mb-4">
                        <svg className="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        正在确认支付结果...
                    </div>
                    <p className="text-gray-400 text-sm">如果您已完成支付，请稍候</p>
                </div>
            )}

            {status === 'success' && (
                <div className="text-center">
                    <div className="mb-6">
                        <svg className="w-16 h-16 mx-auto text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                    </div>
                    <h2 className="text-2xl font-bold text-white mb-4">支付成功！</h2>
                    <p className="text-gray-300 mb-2">会员已开通，即将跳转到登录页...</p>
                    <p className="text-gray-500 text-sm">请重新登录即可使用</p>
                </div>
            )}

            {status === 'error' && (
                <div className="text-center">
                    <div className="mb-6">
                        <svg className="w-16 h-16 mx-auto text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                    </div>
                    <h2 className="text-2xl font-bold text-white mb-4">创建订单失败</h2>
                    <p className="text-red-300 mb-6">{errorMsg}</p>
                    <button
                        onClick={() => router.replace('/login')}
                        className="py-3 px-6 bg-gradient-to-r from-purple-600 to-pink-600 text-white font-semibold rounded-lg"
                    >
                        返回登录
                    </button>
                </div>
            )}

            {status === 'checking' && (
                <div className="mt-6 text-center">
                    <button
                        onClick={() => {
                            if (pollRef.current) clearInterval(pollRef.current);
                            router.replace('/login');
                        }}
                        className="text-purple-300 hover:text-purple-200 text-sm"
                    >
                        返回登录
                    </button>
                </div>
            )}
        </div>
    );
}

export default function PayPage() {
    return (
        <div className="min-h-dvh flex items-center justify-center">
            <Suspense fallback={
                <div className="w-full max-w-md p-8 bg-white/10 backdrop-blur-lg rounded-2xl shadow-2xl border border-white/20 text-center">
                    <svg className="animate-spin h-12 w-12 mx-auto text-purple-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                </div>
            }>
                <PayContent />
            </Suspense>
        </div>
    );
}
