"use client";

import { client } from "@/lib/auth-client";
import { Button } from "@nice/ui/components/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@nice/ui/components/card";
import { Input } from "@nice/ui/components/input";
import { Label } from "@nice/ui/components/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@nice/ui/components/tabs";
import { toast } from "@nice/ui/components/sonner";
import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";

export default function SignInPage() {
    const [loginCredentials, setLoginCredentials] = useState({
        email: "",
        username: "",
        password: ""
    });
    const [registerCredentials, setRegisterCredentials] = useState({
        email: "",
        username: "",
        password: "",
        confirmPassword: "",
        name: ""
    });
    const [isLoading, setIsLoading] = useState(false);
    const [currentTab, setCurrentTab] = useState("login");
    const router = useRouter();
    const searchParams = useSearchParams();
    // 检查是否是从 OIDC Provider 重定向过来的
    const isOIDCFlow = searchParams.get('response_type') === 'code' || searchParams.get('client_id');


    // 登录处理
    const handleSignIn = async (e: React.FormEvent) => {
        e.preventDefault();
        setIsLoading(true);

        try {
            const result = await client.signIn.username({
                username: loginCredentials.username || loginCredentials.email,
                password: loginCredentials.password,
                callbackURL: 'http://localhost:3000/dashboard'
            });

            if (result.data) {
                toast.success("登录成功！");

                // 如果是 OIDC 流程，重定向回原始请求
                if (isOIDCFlow) {
                    // 获取所有查询参数并重建 URL
                    const params = new URLSearchParams(window.location.search);
                    const redirectUrl = `http://localhost:3001/api/auth/oauth2/authorize?${params.toString()}`;
                    window.location.href = redirectUrl;
                } else {
                    router.push('/dashboard');
                }
            } else if (result.error) {
                toast.error(`登录失败: ${result.error.message}`);
            }
        } catch (error: any) {
            console.error("登录失败:", error);
            toast.error(`登录失败: ${error.message || "未知错误"}`);
        } finally {
            setIsLoading(false);
        }
    };

    // 注册处理
    const handleSignUp = async (e: React.FormEvent) => {
        e.preventDefault();

        if (registerCredentials.password !== registerCredentials.confirmPassword) {
            toast.error("密码不匹配");
            return;
        }

        setIsLoading(true);

        try {
            const result = await client.signUp.email({
                email: registerCredentials.email,
                password: registerCredentials.password,
                name: registerCredentials.name,
                username: registerCredentials.username,
                callbackURL: 'http://localhost:3000/dashboard'
            });

            if (result.data) {
                toast.success("注册成功！");

                // 如果是 OIDC 流程，重定向回原始请求
                if (isOIDCFlow) {
                    const params = new URLSearchParams(window.location.search);
                    const redirectUrl = `http://localhost:3001/api/auth/oauth2/authorize?${params.toString()}`;
                    window.location.href = redirectUrl;
                } else {
                    router.push('/dashboard');
                }
            } else if (result.error) {
                toast.error(`注册失败: ${result.error.message}`);
            }
        } catch (error: any) {
            console.error("注册失败:", error);
            toast.error(`注册失败: ${error.message || "未知错误"}`);
        } finally {
            setIsLoading(false);
        }
    };



    return (
        <div className="container mx-auto p-6 max-w-md">
            <div className="mb-4 text-center">
                <Button
                    onClick={() => router.push('/test')}
                    variant="ghost"
                    size="sm"
                >
                    ← 返回 OIDC 测试页面
                </Button>
            </div>

            <Card>
                <CardHeader className="text-center">
                    <CardTitle className="text-2xl">
                        {isOIDCFlow ? "授权登录" : "用户认证"}
                    </CardTitle>
                    <CardDescription>
                        {isOIDCFlow ? (
                            <span>OIDC Provider 授权登录</span>
                        ) : (
                            <span>登录或注册您的账户</span>
                        )}
                    </CardDescription>
                </CardHeader>
                <CardContent>
                    {isOIDCFlow && (
                        <div className="mb-4 p-3 bg-blue-50 dark:bg-blue-950 rounded-md">
                            <p className="text-sm text-blue-800 dark:text-blue-200">
                                检测到 OIDC 授权流程。登录或注册后将继续完成授权。
                            </p>
                        </div>
                    )}

                    <Tabs value={currentTab} onValueChange={setCurrentTab}>
                        <TabsList className="grid w-full grid-cols-2">
                            <TabsTrigger value="login">登录</TabsTrigger>
                            <TabsTrigger value="register">注册</TabsTrigger>
                        </TabsList>

                        {/* 登录表单 */}
                        <TabsContent value="login" className="space-y-4 mt-4">
                            <form onSubmit={handleSignIn} className="space-y-4">
                                <div className="space-y-2">
                                    <Label htmlFor="login-email">邮箱或用户名</Label>
                                    <Input
                                        id="login-email"
                                        type="text"
                                        placeholder="输入邮箱或用户名"
                                        value={loginCredentials.email}
                                        onChange={(e) => setLoginCredentials({ ...loginCredentials, email: e.target.value })}
                                        disabled={isLoading}
                                        required
                                    />
                                </div>

                                <div className="space-y-2">
                                    <Label htmlFor="login-password">密码</Label>
                                    <Input
                                        id="login-password"
                                        type="password"
                                        placeholder="输入密码"
                                        value={loginCredentials.password}
                                        onChange={(e) => setLoginCredentials({ ...loginCredentials, password: e.target.value })}
                                        disabled={isLoading}
                                        required
                                    />
                                </div>

                                <Button type="submit" className="w-full" disabled={isLoading}>
                                    {isLoading ? "登录中..." : "登录"}
                                </Button>
                            </form>
                        </TabsContent>

                        {/* 注册表单 */}
                        <TabsContent value="register" className="space-y-4 mt-4">
                            <form onSubmit={handleSignUp} className="space-y-4">
                                <div className="space-y-2">
                                    <Label htmlFor="register-name">姓名</Label>
                                    <Input
                                        id="register-name"
                                        type="text"
                                        placeholder="输入您的姓名"
                                        value={registerCredentials.name}
                                        onChange={(e) => setRegisterCredentials({ ...registerCredentials, name: e.target.value })}
                                        disabled={isLoading}
                                        required
                                    />
                                </div>

                                <div className="space-y-2">
                                    <Label htmlFor="register-username">用户名</Label>
                                    <Input
                                        id="register-username"
                                        type="text"
                                        placeholder="输入用户名"
                                        value={registerCredentials.username}
                                        onChange={(e) => setRegisterCredentials({ ...registerCredentials, username: e.target.value })}
                                        disabled={isLoading}
                                        required
                                    />
                                </div>

                                <div className="space-y-2">
                                    <Label htmlFor="register-email">邮箱</Label>
                                    <Input
                                        id="register-email"
                                        type="email"
                                        placeholder="输入邮箱地址"
                                        value={registerCredentials.email}
                                        onChange={(e) => setRegisterCredentials({ ...registerCredentials, email: e.target.value })}
                                        disabled={isLoading}
                                        required
                                    />
                                </div>

                                <div className="space-y-2">
                                    <Label htmlFor="register-password">密码</Label>
                                    <Input
                                        id="register-password"
                                        type="password"
                                        placeholder="输入密码"
                                        value={registerCredentials.password}
                                        onChange={(e) => setRegisterCredentials({ ...registerCredentials, password: e.target.value })}
                                        disabled={isLoading}
                                        required
                                    />
                                </div>

                                <div className="space-y-2">
                                    <Label htmlFor="register-confirm-password">确认密码</Label>
                                    <Input
                                        id="register-confirm-password"
                                        type="password"
                                        placeholder="再次输入密码"
                                        value={registerCredentials.confirmPassword}
                                        onChange={(e) => setRegisterCredentials({ ...registerCredentials, confirmPassword: e.target.value })}
                                        disabled={isLoading}
                                        required
                                    />
                                </div>

                                <Button type="submit" className="w-full" disabled={isLoading}>
                                    {isLoading ? "注册中..." : "注册"}
                                </Button>
                            </form>
                        </TabsContent>
                    </Tabs>

                    {isOIDCFlow && (
                        <div className="mt-4">
                            <Button
                                onClick={() => router.push('/test')}
                                variant="ghost"
                                className="w-full"
                            >
                                返回测试页面
                            </Button>
                        </div>
                    )}
                </CardContent>
            </Card>
        </div>
    );
}
