"use client";

import { useEffect, useRef, useState } from "react";
import { useSearchParams } from "next/navigation";
import { Loader2 } from "lucide-react";
import { authClient } from "@/lib/auth-client";
import { MagicLinkForm } from "./magic-link-form";
import { MicrosoftButton } from "./microsoft-button";
import { Separator } from "@/components/ui/separator";

export function SignInForm() {
  const searchParams = useSearchParams();
  const callbackUrl = searchParams.get("callbackUrl") || "/";
  const isMobileFlow = callbackUrl.startsWith("/mobile");
  const [autoRedirecting, setAutoRedirecting] = useState(isMobileFlow);
  const triggered = useRef(false);

  useEffect(() => {
    if (!isMobileFlow || triggered.current) return;
    triggered.current = true;
    authClient.signIn
      .social({ provider: "microsoft", callbackURL: callbackUrl })
      .then((result) => {
        if (result?.error) setAutoRedirecting(false);
      })
      .catch(() => setAutoRedirecting(false));
  }, [isMobileFlow, callbackUrl]);

  if (autoRedirecting) {
    return (
      <div className="flex flex-col items-center gap-3 py-8">
        <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
        <p className="text-sm text-muted-foreground">Signing you in with Microsoft 365…</p>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <MicrosoftButton callbackURL={callbackUrl} />

      <div className="relative">
        <div className="absolute inset-0 flex items-center">
          <Separator className="w-full" />
        </div>
        <div className="relative flex justify-center text-xs uppercase">
          <span className="bg-white dark:bg-slate-900 px-2 text-muted-foreground">
            Or continue with email
          </span>
        </div>
      </div>

      <MagicLinkForm />
    </div>
  );
}
