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;
}; burada splash screen e gif ekleyebiliyor muyuz? assets/camel.gif i ekranın ortasına koyalım