"use client";

import { useState } from "react";
import { BriefcaseBusiness, Code2, Globe2 } from "lucide-react";
import { createClient } from "@/lib/supabase/client";
import { buildAuthCallbackUrl } from "@/lib/auth";
import { formatAuthMethodList } from "@/lib/organization-auth";
import { Button } from "@/components/ui/button";
import type { AuthMethod } from "@/types";
import type { AuthPolicyPreview } from "@/hooks/use-auth-policy-preview";

type OAuthProvider = "google" | "github" | "azure";

const PROVIDERS: Array<{
  id: OAuthProvider;
  label: string;
  icon: typeof Globe2;
}> = [
  { id: "google", label: "Google", icon: Globe2 },
  { id: "github", label: "GitHub", icon: Code2 },
  { id: "azure", label: "Microsoft", icon: BriefcaseBusiness },
];

interface OAuthButtonsProps {
  nextPath?: string;
  email?: string;
  policyPreview?: AuthPolicyPreview | null;
}

const PROVIDER_TO_METHOD: Record<OAuthProvider, AuthMethod> = {
  google: "google",
  github: "github",
  azure: "azure",
};

export function OAuthButtons({
  nextPath = "/",
  email = "",
  policyPreview = null,
}: OAuthButtonsProps) {
  const [loadingProvider, setLoadingProvider] = useState<OAuthProvider | null>(null);
  const [error, setError] = useState<string | null>(null);

  async function handleProvider(provider: OAuthProvider) {
    const supabase = createClient();
    const normalizedEmail = email.trim().toLowerCase();
    setError(null);
    setLoadingProvider(provider);

    if (
      normalizedEmail &&
      policyPreview &&
      !policyPreview.allowedMethods.includes(PROVIDER_TO_METHOD[provider])
    ) {
      setError(`This email must use one of: ${formatAuthMethodList(policyPreview.allowedMethods)}.`);
      setLoadingProvider(null);
      return;
    }

    try {
      const { error: oauthError } = await supabase.auth.signInWithOAuth({
        provider,
        options: {
          redirectTo: buildAuthCallbackUrl(nextPath),
        },
      });

      if (oauthError) {
        setError(oauthError.message);
        setLoadingProvider(null);
      }
    } catch {
      setError("Der Auth-Dienst ist gerade nicht erreichbar.");
      setLoadingProvider(null);
    }
  }

  return (
    <div className="space-y-3">
      <div className="grid gap-2">
        {PROVIDERS.map((provider) => (
          <Button
            key={provider.id}
            type="button"
            variant="outline"
            className="w-full justify-start"
            onClick={() => void handleProvider(provider.id)}
            disabled={loadingProvider !== null}
          >
            <provider.icon className="h-4 w-4" />
            {loadingProvider === provider.id
              ? `Connecting ${provider.label}...`
              : `Continue with ${provider.label}`}
          </Button>
        ))}
      </div>
      {error && <p className="text-sm text-destructive">{error}</p>}
      <p className="text-xs text-muted-foreground">
        OAuth providers work as soon as they are enabled in your Supabase auth settings.
      </p>
    </div>
  );
}
