import { createClient, SupabaseClient } from '@supabase/supabase-js'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { Platform } from 'react-native'

// Web-kompatible Storage-Lösung
const getStorageAdapter = () => {
  if (Platform.OS === 'web') {
    // Web Storage Adapter
    return {
      getItem: async (key: string) => {
        if (typeof window !== 'undefined' && window.localStorage) {
          return window.localStorage.getItem(key);
        }
        return null;
      },
      setItem: async (key: string, value: string) => {
        if (typeof window !== 'undefined' && window.localStorage) {
          window.localStorage.setItem(key, value);
        }
      },
      removeItem: async (key: string) => {
        if (typeof window !== 'undefined' && window.localStorage) {
          window.localStorage.removeItem(key);
        }
      }
    };
  } else {
    // React Native Storage
    return AsyncStorage;
  }
};

// Sichere Konfiguration mit Fallbacks
const getSupabaseConfig = () => {
  const supabaseUrl = process.env.EXPO_PUBLIC_SUPABASE_URL;
  const supabaseAnonKey = process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY;

  console.log('🔍 Supabase Konfiguration prüfen:');
  console.log('URL:', supabaseUrl);
  console.log('Key vorhanden:', !!supabaseAnonKey);

  // Prüfe ob die Werte korrekt sind und nicht die Platzhalter
  if (!supabaseUrl || 
      supabaseUrl === 'https://your-project-id.supabase.co' || 
      supabaseUrl === 'https://your-project.supabase.co' ||
      supabaseUrl === 'https://mock.supabase.co' ||
      !supabaseAnonKey || 
      supabaseAnonKey === 'your-anon-key-here' ||
      supabaseAnonKey === 'your-anon-key' ||
      supabaseAnonKey === 'mock-key') {
    console.warn('⚠️ Supabase nicht korrekt konfiguriert! Verwende Mock-Client.');
    return null; // Keine gültige Konfiguration
  }

  console.log('✅ Supabase Konfiguration sieht korrekt aus');
  return {
    url: supabaseUrl,
    key: supabaseAnonKey
  };
};

const config = getSupabaseConfig();

// Erstelle Client nur wenn Konfiguration gültig ist
let supabase: SupabaseClient;
if (config) {
  try {
    console.log('🔧 Erstelle Supabase Client für', Platform.OS === 'web' ? 'Web' : 'Expo Go');
    const storageAdapter = getStorageAdapter();
    
    supabase = createClient(config.url, config.key, {
      auth: {
        autoRefreshToken: true,
        persistSession: true,
        detectSessionInUrl: Platform.OS === 'web',
        // Platform-spezifische Storage
        storage: storageAdapter,
        storageKey: 'supabase.auth.token'
      }
    });
    console.log('✅ Supabase Client mit', Platform.OS === 'web' ? 'localStorage' : 'AsyncStorage', 'erfolgreich erstellt');
  } catch (error) {
    console.error('❌ Fehler beim Erstellen des Supabase Clients:', error);
    // Fallback zu Mock-Client
    supabase = createMockClient();
  }
} else {
  console.log('⚠️ Verwende Mock-Client für Supabase');
  supabase = createMockClient();
}

// Mock-Client für Entwicklung
function createMockClient(): any {
  return {
    auth: {
      getUser: async () => ({ 
        data: { user: null }, 
        error: { message: 'Supabase nicht konfiguriert' } 
      }),
      signInWithPassword: async () => ({ 
        data: null, 
        error: { message: 'Supabase nicht konfiguriert. Bitte setze EXPO_PUBLIC_SUPABASE_URL und EXPO_PUBLIC_SUPABASE_ANON_KEY in deiner .env Datei.' } 
      }),
      signUp: async () => ({ 
        data: null, 
        error: { message: 'Supabase nicht konfiguriert. Bitte setze EXPO_PUBLIC_SUPABASE_URL und EXPO_PUBLIC_SUPABASE_ANON_KEY in deiner .env Datei.' } 
      }),
      signOut: async () => ({ error: null })
    },
    from: () => ({
      select: () => ({
        limit: () => Promise.resolve({ 
          data: null, 
          error: { message: 'Supabase nicht konfiguriert' } 
        })
      })
    })
  };
}

export { supabase }; 