import React, { useEffect, useState } from 'react';
import { ClerkProvider } from '@clerk/clerk-react';
import { trTR } from '@clerk/localizations';
import { siteSettingsApi, adminAdvancedApi } from '@/db/api';
import { Loader2 } from 'lucide-react';
import { ClerkAvailabilityContext } from '@/contexts/ClerkAvailabilityContext';

interface ClerkDynamicProviderProps {
  children: React.ReactNode;
}

export function ClerkDynamicProvider({ children }: ClerkDynamicProviderProps) {
  const [publishableKey, setPublishableKey] = useState<string | null>(
    import.meta.env.VITE_CLERK_PUBLISHABLE_KEY || null
  );
  const [loading, setLoading] = useState(!import.meta.env.VITE_CLERK_PUBLISHABLE_KEY);

  useEffect(() => {
    async function fetchKey() {
      // If we already have a key from env, we're good
      if (publishableKey && publishableKey.length > 5) {
        setLoading(false);
        return;
      }

      try {
        console.log('🔍 Checking for Clerk Publishable Key in database...');
        
        // 1. Try site_settings table (the specific field)
        const setting = await siteSettingsApi.getByKey('clerk_publishable_key');
        if (setting?.value && setting.value.length > 5) {
          console.log('✅ Found Clerk key in site_settings');
          setPublishableKey(setting.value);
          setLoading(false);
          return;
        }

        // 2. Try admin_api_keys table (the general API keys table)
        const apiKeys = await adminAdvancedApi.getApiKeys();
        const clerkKey = apiKeys.find((k: any) => 
          k.key === 'VITE_CLERK_PUBLISHABLE_KEY' || 
          k.key === 'CLERK_PUBLISHABLE_KEY' ||
          k.key === 'clerk_publishable_key'
        );

        if (clerkKey?.value && clerkKey.value.length > 5) {
          console.log('✅ Found Clerk key in admin_api_keys');
          setPublishableKey(clerkKey.value);
          setLoading(false);
          return;
        }

        console.warn('⚠️ No Clerk Publishable Key found in database or environment.');
      } catch (error) {
        console.error('❌ Clerk key fetching error:', error);
      } finally {
        setLoading(false);
      }
    }

    fetchKey();
  }, []); // Only run once on mount

  const value = {
    isClerkAvailable: !!publishableKey && publishableKey.startsWith('pk_'),
    publishableKey,
    loading,
  };

  if (loading) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen gap-4">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
        <p className="text-sm text-muted-foreground">Kimlik doğrulama sistemi hazırlanıyor...</p>
      </div>
    );
  }

  return (
    <ClerkAvailabilityContext.Provider value={value}>
      {publishableKey ? (
        <ClerkProvider 
          publishableKey={publishableKey}
          localization={trTR}
          appearance={{
            variables: {
              colorPrimary: '#ea580c',
              colorBackground: '#ffffff',
              colorText: '#1f2937'
            },
            elements: {
              formButtonPrimary: 'bg-primary hover:bg-primary/90',
              card: 'shadow-lg',
              headerTitle: 'text-2xl font-bold',
              headerSubtitle: 'text-muted-foreground'
            }
          }}
        >
          {children}
        </ClerkProvider>
      ) : (
        <>{children}</>
      )}
    </ClerkAvailabilityContext.Provider>
  );
}
