'use client';

import { useEffect, useState } from 'react';

import type { Provider } from '@supabase/supabase-js';

import { authConfig } from '../config';
import { getCachedAuthConfig } from '../config/dynamic-auth.config';

interface AuthConfig {
  providers: {
    password: boolean;
    magicLink: boolean;
    oAuth: Provider[];
  };
}

interface UseAuthConfigResult {
  config: AuthConfig | null;
  loading: boolean;
  error: Error | null;
  refetch: () => Promise<void>;
}

export function useAuthConfig(): UseAuthConfigResult {
  const [config, setConfig] = useState<AuthConfig | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  const fetchConfig = async () => {
    try {
      setLoading(true);
      setError(null);
      const authConfig = await getCachedAuthConfig();
      setConfig(authConfig);
    } catch (err) {
      console.error('Failed to fetch auth config', err);
      setError(
        err instanceof Error ? err : new Error('Failed to fetch auth config'),
      );
      setConfig(authConfig);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchConfig();
  }, []);

  return {
    config,
    loading,
    error,
    refetch: fetchConfig,
  };
}

export function useProviderEnabled(
  provider: 'password' | 'magicLink' | Provider,
) {
  const { config, loading, error } = useAuthConfig();

  const isEnabled = (() => {
    if (!config) return false;

    switch (provider) {
      case 'password':
        return config.providers.password;
      case 'magicLink':
        return config.providers.magicLink;
      default:
        return config.providers.oAuth.includes(provider);
    }
  })();

  return {
    enabled: isEnabled,
    loading,
    error,
  };
}
