"use client";

import { useCallback, useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { getDiscourseSSOUrl } from "@/actions/discourse-sso-url";

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

export function Authorizing() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [error, setError] = useState<unknown | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  const signInCallback = useCallback(async () => {
    try {
      const url = await getDiscourseSSOUrl(searchParams.toString());
      router.push(url);
    } catch (error) {
      setError(error);
      setIsLoading(false);
    }
  }, [router, searchParams]);

  useEffect(() => {
    // Delay 3s get sso url go to ...
    const timer = setTimeout(signInCallback, 3);
    return () => {
      clearTimeout(timer);
    };
  }, [signInCallback]);

  if (error) {
    return (
      <Card className="w-full">
        <CardHeader className="space-y-4 text-center">
          <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-red-100">
            <div className="h-8 w-8 text-red-600">❌</div>
          </div>
          <CardTitle className="text-2xl font-semibold text-red-600">
            授权失败
          </CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-center text-gray-500">
            {error instanceof Error
              ? error.message
              : "授权异常，登录失败！请稍后重试。"}
          </p>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="w-full">
      <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>
  );
}
