"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();

  async function signIn() {
    try {
      const body: Record<string, any> = {};
      const callbackUrl = searchParams?.get("callbackUrl");

      // 如果是 OAuth 回调，则提取原始的 /oauth/authorize 部分
      if (callbackUrl?.includes("/oauth/authorize")) {
        const url = new URL(callbackUrl);
        body.return_url = `${window.location.origin}${url.pathname}${url.search}`;
      }

      const response = await fetch("/api/auth/q58", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(body),
      });

      if (!response.ok) {
        throw new Error("登录请求失败");
      }

      const data = await response.json();
      window.location.href = data.sso_url;
    } catch (error) {
      console.error("登录错误:", error);
      toast({
        title: "错误",
        description: "登录过程中发生错误，请稍后重试",
        variant: "destructive",
      });
      setIsLoading(false);
    }
  }

  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>
  );
}
