"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { handleAuthorizeAction } from "@/actions/authorizing";

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { ErrorCard } from "@/components/auth/error-card";

interface AuthorizingProps {
  oauth: string;
  clientId: string;
  scope: string;
  redirectUri: string;
}

export function Authorizing({
  oauth,
  clientId,
  scope,
  redirectUri,
}: AuthorizingProps) {
  const [error, setError] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const authorize = async () => {
      try {
        const result = await handleAuthorizeAction(oauth, clientId, scope);
        if (result.error) {
          setError(result.error);
        } else if (result.redirectUrl) {
          const url = await result.redirectUrl;
          window.location.href = url;
        } else {
          setError("授权响应无效");
        }
      } catch (err) {
        console.error("授权过程出错:", err);
        setError(err instanceof Error ? err.message : "授权过程发生未知错误");
      } finally {
        setIsLoading(false);
      }
    };

    authorize();
  }, [oauth, clientId, scope]);

  if (error) {
    return (
      <div className="flex min-h-screen items-center justify-center p-4">
        <ErrorCard
          title="授权失败"
          description={error}
          redirectUri={redirectUri}
          error="access_denied"
          errorDescription={error}
        />
      </div>
    );
  }

  return (
    <Card className="w-full max-w-md">
      <CardHeader className="space-y-4 text-center">
        <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-blue-100">
          <div className="h-8 w-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent"></div>
        </div>
        <CardTitle className="text-2xl font-semibold">正在处理授权</CardTitle>
      </CardHeader>
      <CardContent>
        <p className="text-center text-gray-500">
          {isLoading ? "请稍候，我们正在处理您的授权请求" : "正在跳转..."}
        </p>
      </CardContent>
    </Card>
  );
}
