import React, { createContext, useContext, useState, useEffect } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import * as Localization from 'expo-localization';
import { I18n } from 'i18n-js';
import { Appearance } from 'react-native';
import { setStatusBarStyle } from 'expo-status-bar';
import { useFonts } from 'expo-font';
import * as SplashScreen from 'expo-splash-screen';

import { darkTheme } from '../themes/darkTheme';
import { lightTheme } from '../themes/lightTheme';
import { vibrantTheme } from '../themes/vibrantTheme';
import { secretGardenTheme } from '../themes/secretGardenTheme';
import { slateDarkTheme } from '../themes/slateDarkTheme';
import { blackOrangeTheme } from '../themes/blackOrangeTheme';

// Splash screen'in otomatik kapanmasını engelleyelim
SplashScreen.preventAutoHideAsync();

const i18n = new I18n({
  en: require('../locales/en.json'),
  tr: require('../locales/tr.json'),
});

i18n.enableFallback = true;

const ThemeAndLanguageContext = createContext();

const FONT_FAMILIES = {
  Mirza: {
    regular: 'Mirza_400Regular',
    bold: 'Mirza_600SemiBold'
  },
  Amiri: {
    regular: 'Amiri_400Regular',
    bold: 'Amiri_700Bold'
  },
  NotoNaskhArabic: {
    regular: 'NotoNaskhArabic_400Regular',
    bold: 'NotoNaskhArabic_600SemiBold'
  },
  NotoSansArabic: {
    regular: 'NotoSansArabic_400Regular',
    bold: 'NotoSansArabic_600SemiBold'
  },
  Poppins: {
    regular: 'Poppins-Regular',
    bold: 'Poppins-Bold'
  }
};

export const ThemeAndLanguageProvider = ({ children }) => {
  const [themeType, setThemeType] = useState('light');
  const [locale, setLocale] = useState(Localization.locale);
  const [isLoading, setIsLoading] = useState(true);
  const [selectedFontFamily, setSelectedFontFamily] = useState('Mirza');

  const [fontsLoaded, fontError] = useFonts({
    'Mirza_400Regular': require('../../assets/fonts/Mirza-Regular.ttf'),
    'Mirza_600SemiBold': require('../../assets/fonts/Mirza-Bold.ttf'),
    'Amiri_400Regular': require('../../assets/fonts/Amiri-Regular.ttf'),
    'Amiri_700Bold': require('../../assets/fonts/Amiri-Bold.ttf'),
    'NotoNaskhArabic_400Regular': require('../../assets/fonts/NotoNaskhArabic-Regular.ttf'),
    'NotoNaskhArabic_600SemiBold': require('../../assets/fonts/NotoNaskhArabic-Bold.ttf'),
    'NotoSansArabic_400Regular': require('../../assets/fonts/NotoSansArabic-Regular.ttf'),
    'NotoSansArabic_600SemiBold': require('../../assets/fonts/NotoSansArabic-Bold.ttf'),
    'Poppins-Regular': require('../../assets/fonts/Poppins-Regular.ttf'),
    'Poppins-Bold': require('../../assets/fonts/Poppins-Bold.ttf'),
  });

  // Font yükleme durumunu kontrol eden useEffect
  useEffect(() => {
    if (fontsLoaded || fontError) {
      // Fontlar yüklendiğinde veya hata olduğunda splash screen'i gizle
      SplashScreen.hideAsync();
    }
  }, [fontsLoaded, fontError]);

  useEffect(() => {
    if (fontError) {
      console.error('Font loading error:', fontError);
    }
  }, [fontError]);

  useEffect(() => {
    const loadSettings = async () => {
      try {
        const storedTheme = await AsyncStorage.getItem('theme');
        const storedLocale = await AsyncStorage.getItem('locale');
        const storedFontFamily = await AsyncStorage.getItem('fontFamily');

        if (storedTheme) {
          setThemeType(storedTheme);
        } else {
          const defaultTheme = Appearance.getColorScheme();
          setThemeType(defaultTheme || 'light');
        }

        if (storedLocale) {
          setLocale(storedLocale);
          i18n.locale = storedLocale;
        } else {
          const defaultLocale = Localization.locale.startsWith('tr') ? 'tr' : 'en';
          i18n.locale = defaultLocale;
          setLocale(defaultLocale);
        }

        if (storedFontFamily && FONT_FAMILIES[storedFontFamily]) {
          setSelectedFontFamily(storedFontFamily);
        }
      } catch (error) {
        console.error('Error loading settings:', error);
      } finally {
        if (fontsLoaded) {
          setIsLoading(false);
        }
      }
    };

    loadSettings();
  }, [fontsLoaded]);

  // Font yüklenmesi tamamlanmadıysa null dön
  if (!fontsLoaded && !fontError) {
    return null;
  }

  // Font yükleme hatası varsa fallback font kullan
  if (fontError) {
    console.warn('Using fallback font due to loading error');
  }

  const theme = themeType === 'vibrant' 
    ? vibrantTheme 
    : themeType === 'secretGarden'
      ? secretGardenTheme
      : themeType === 'slateDark'
        ? slateDarkTheme
        : themeType === 'blackOrange'
          ? blackOrangeTheme
          : themeType === 'dark'
            ? darkTheme
            : lightTheme;

  const changeTheme = async (newThemeType) => {
    setThemeType(newThemeType);
    await AsyncStorage.setItem('theme', newThemeType);

    if (newThemeType === 'dark' || newThemeType === 'slateDark' || newThemeType === 'blackOrange') {
      setStatusBarStyle('light');
    } else {
      setStatusBarStyle('dark');
    }
  };

  const changeLanguage = async (newLocale) => {
    setLocale(newLocale);
    i18n.locale = newLocale;
    await AsyncStorage.setItem('locale', newLocale);
  };

  const updateFontFamily = async (newFontFamily) => {
    if (FONT_FAMILIES[newFontFamily]) {
      setSelectedFontFamily(newFontFamily);
      await AsyncStorage.setItem('fontFamily', newFontFamily);
    }
  };

  const contextValue = {
    theme,
    themeType,
    locale,
    setThemeType: changeTheme,
    changeLanguage,
    t: (key, options) => i18n.t(key, options),
    arabicFont: FONT_FAMILIES[selectedFontFamily].regular,
    arabicFontBold: FONT_FAMILIES[selectedFontFamily].bold,
    setFontFamily: updateFontFamily,
    poppinsRegular: FONT_FAMILIES.Poppins.regular,
    poppinsBold: FONT_FAMILIES.Poppins.bold,
    currentFontFamily: selectedFontFamily,
    availableFontFamilies: Object.keys(FONT_FAMILIES),
  };

  return (
    <ThemeAndLanguageContext.Provider value={contextValue}>
      {children}
    </ThemeAndLanguageContext.Provider>
  );
};

export const useThemeAndLanguage = () => {
  const context = useContext(ThemeAndLanguageContext);
  if (context === undefined) {
    throw new Error('useThemeAndLanguage must be used within a ThemeAndLanguageProvider');
  }
  return context;
}; bu kodu incele;

bu font settings açıldığında hata alıyoruz:
import React from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useThemeAndLanguage } from '../utils/ThemeAndLanguageContext'; // Path'i kendi yapınıza göre ayarlayın

const FontSettings = ({
  fontSize,
  increaseFontSize,
  decreaseFontSize,
  theme,
  t,
}) => {
  const { 
    setFontFamily, 
    currentFontFamily,
    availableFontFamilies,
    arabicFont 
  } = useThemeAndLanguage();

  return (
    <View style={styles.settingsContent}>
      {/* Example Card */}
      <View style={[styles.exampleCard, { backgroundColor: theme.cardBackground }]}>
        <Text style={[
          styles.exampleText, 
          { 
            fontSize: fontSize * 1.4, 
            fontFamily: arabicFont,
            color: theme.textColor 
          }
        ]}>
          (هذا مثال على الكتابة بالعربية)
        </Text>
      </View>
      
      {/* Font Size Controls */}
      <View style={styles.fontSizeControls}>
        <TouchableOpacity onPress={increaseFontSize} style={styles.fontSizeButton}>
          <Ionicons name="add-circle-outline" size={40} color={theme.primaryColor} />
          <Text style={[styles.fontSizeButtonText, { color: theme.textColor }]}>
            {t('increaseFontSize')}
          </Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={decreaseFontSize} style={styles.fontSizeButton}>
          <Ionicons name="remove-circle-outline" size={40} color={theme.primaryColor} />
          <Text style={[styles.fontSizeButtonText, { color: theme.textColor }]}>
            {t('decreaseFontSize')}
          </Text>
        </TouchableOpacity>
      </View>
      
      {/* Font Family Selection */}
      <View style={styles.fontOptionsContainer}>
        {availableFontFamilies.map((fontFamily) => (
          <TouchableOpacity
            key={fontFamily}
            style={[
              styles.fontOption,
              { 
                backgroundColor: theme.cardBackground,
                borderColor: currentFontFamily === fontFamily ? theme.primaryColor : 'transparent',
                borderWidth: currentFontFamily === fontFamily ? 2 : 0,
              }
            ]}
            onPress={() => setFontFamily(fontFamily)}
          >
            <Text style={[styles.fontOptionText, { color: theme.textColor }]}>
              {fontFamily}
            </Text>
            <Text style={[
              styles.fontOptionSample, 
              { 
                fontFamily: fontFamily,
                color: theme.textColor 
              }
            ]}>
              (اقرأ العربية)
            </Text>
          </TouchableOpacity>
        ))}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  settingsContent: {
    flexGrow: 1,
  },
  exampleCard: {
    backgroundColor: 'white',
    borderRadius: 10,
    padding: 15,
    marginVertical: 20,
    width: '90%',
    alignSelf: 'center',

  },
  exampleText: {
    textAlign: 'center',
  },
  fontSizeControls: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    width: '100%',
    marginBottom: 20,
  },
  fontSizeButton: {
    alignItems: 'center',
  },
  fontSizeButtonText: {
    marginTop: 5,
    fontSize: 12,
    color: 'gray',
    textAlign: 'center',
  },
  fontOptionsContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-around',
    marginTop: 20,
    alignSelf: 'center',
  },
  fontOption: {
    width: '45%',

    backgroundColor: 'white',
    borderRadius: 10,
    padding: 10,
    marginBottom: 20,
    alignItems: 'center',
  },
  fontOptionText: {
    fontSize: 16,
    marginBottom: 5,
    textAlign: 'center',
  },
  fontOptionSample: {
    fontSize: 18,
  },
});

export default FontSettings;

 WARN  fontFamily "Mirza" is not a system font and has not been loaded through expo-font.
 WARN  fontFamily "Amiri" is not a system font and has not been loaded through expo-font.
 WARN  fontFamily "NotoNaskhArabic" is not a system font and has not been loaded through expo-font.
 WARN  fontFamily "NotoSansArabic" is not a system font and has not been loaded through expo-font.
 WARN  fontFamily "Poppins" is not a system font and has not been loaded through expo-font.