'use client';

import { Button } from '@nice/ui/components/button'
import { oidcClient } from '@/lib/auth/oidc-client';
import { useEffect, useState } from 'react';

export default function AuthTestPage() {
    const [redirectUri, setRedirectUri] = useState('');

    useEffect(() => {
        // 设置回调 URI
        setRedirectUri(`${window.location.origin}/auth/callback`);
    }, []);

    const handleLogin = () => {
        if (!redirectUri) return;

        // 构建授权 URL
        const authUrl = oidcClient.buildAuthorizationUrl({
            redirectUri,
            state: 'test-state',
            scope: 'openid profile email',
        });

        // 保存状态到 sessionStorage（用于回调验证）
        sessionStorage.setItem('oauth_state', 'test-state');
        sessionStorage.setItem('oauth_redirect_uri', redirectUri);

        // 跳转到授权页面
        window.location.href = authUrl;
    };

    return (
        <div className="flex items-center justify-center">
            <div className="max-w-md w-full space-y-8">
                <div>
                    <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
                        统一身份认证测试
                    </h2>
                    <p className="mt-2 text-center text-sm text-gray-600">
                        点击按钮跳转到授权登录页面
                    </p>
                </div>

                <div className="mt-8 space-y-6">
                    <Button
                        onClick={handleLogin}
                        className="group relative w-full flex justify-center py-3 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                        disabled={!redirectUri}
                    >
                        {!redirectUri ? '正在初始化...' : '统一身份认证登录'}
                    </Button>
                </div>

                {redirectUri && (
                    <div className="mt-4 text-xs text-gray-500 text-center">
                        <p>回调地址: {redirectUri}</p>
                    </div>
                )}
            </div>
        </div>
    );
}
