"use client";

import * as React from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Loader2, MessageCircleCode } from "lucide-react";

import { cn } from "@/lib/utils";
import { useToast } from "@/hooks/use-toast";
import { buttonVariants } from "@/components/ui/button";

interface DiscourseData {
  sso_url: string;
}

export function UserAuthForm({
  className,
  ...props
}: React.HTMLAttributes<HTMLDivElement>) {
  const [isLoading, setIsLoading] = React.useState<boolean>(false);
  const router = useRouter();
  const { toast } = useToast();
  const searchParams = useSearchParams();

  const signIn = () => {
    React.startTransition(async () => {
      try {
        // 获取当前的 OAuth 参数
        const params = new URLSearchParams();
        if (searchParams) {
          const keys = Array.from(searchParams.keys());
          keys.forEach((key) => {
            const value = searchParams.get(key);
            if (value) params.set(key, value);
          });
        }

        const response = await fetch("/api/auth/q58", {
          method: "POST",
          body: params,
        });

        if (!response.ok) {
          throw new Error(response.statusText);
        }

        const data: DiscourseData = await response.json();
        if (data.sso_url) {
          router.push(data.sso_url);
        } else {
          throw new Error("Invalid SSO URL");
        }
      } catch (error) {
        setIsLoading(false);
        toast({
          variant: "destructive",
          title: "内部服务异常",
          description: error instanceof Error ? error.message : "未知错误",
        });
      }
    });
  };

  return (
    <div className={cn("grid gap-3", className)} {...props}>
      <button
        type="button"
        className={cn(buttonVariants({ variant: "outline" }))}
        onClick={() => {
          setIsLoading(true);
          signIn();
        }}
        disabled={isLoading}
      >
        {isLoading ? (
          <Loader2 className="mr-2 size-4 animate-spin" />
        ) : (
          <MessageCircleCode className="mr-2 size-4" />
        )}{" "}
        Q58论坛
      </button>
    </div>
  );
}
