"use client";

import * as React from "react";
import { useRouter } 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 { toast } = useToast();

  const signIn = async () => {
    if (isLoading) return;

    setIsLoading(true);
    try {
      const response = await fetch("/api/auth/q58", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
      });

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

      const data: DiscourseData = await response.json();
      // 直接跳转到 SSO 登录页面
      window.location.href = data.sso_url;
    } catch (error) {
      console.error("登录失败:", error);
      setIsLoading(false);
      toast({
        variant: "destructive",
        title: "登录失败",
        description: "请求失败，请稍后重试",
      });
    }
  };

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