"use client";

import { useState } from "react";
import { Loader2 } from "lucide-react";
import { toast } from "sonner";
import { authClient } from "@/lib/auth-client";
import { Button } from "@/components/ui/button";

// Microsoft logo SVG component
function MicrosoftLogo({ className }: { className?: string }) {
  return (
    <svg
      className={className}
      viewBox="0 0 21 21"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
    >
      <rect x="1" y="1" width="9" height="9" fill="#F25022" />
      <rect x="11" y="1" width="9" height="9" fill="#7FBA00" />
      <rect x="1" y="11" width="9" height="9" fill="#00A4EF" />
      <rect x="11" y="11" width="9" height="9" fill="#FFB900" />
    </svg>
  );
}

interface MicrosoftButtonProps {
  callbackURL?: string;
}

export function MicrosoftButton({ callbackURL = "/" }: MicrosoftButtonProps) {
  const [isLoading, setIsLoading] = useState(false);

  async function handleMicrosoftSignIn() {
    setIsLoading(true);
    try {
      const result = await authClient.signIn.social({
        provider: "microsoft",
        callbackURL,
      });

      if (result.error) {
        toast.error(result.error.message || "Failed to sign in with Microsoft");
        setIsLoading(false);
      }
      // If successful, the user will be redirected to Microsoft's OAuth page
    } catch (error) {
      toast.error("An unexpected error occurred");
      console.error("Microsoft sign-in error:", error);
      setIsLoading(false);
    }
  }

  return (
    <Button
      type="button"
      variant="outline"
      className="w-full"
      onClick={handleMicrosoftSignIn}
      disabled={isLoading}
    >
      {isLoading ? (
        <>
          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
          Connecting...
        </>
      ) : (
        <>
          <MicrosoftLogo className="mr-2 h-4 w-4" />
          Continue with Microsoft 365
        </>
      )}
    </Button>
  );
}
