import React, { createContext, useEffect, useState } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Alert } from 'react-native';

export const SettingsContext = createContext<any>(null);

type SettingsType = {
    url: string,
    username: string,
    password: string,
    systemTheme: boolean,
    darkTheme: boolean,
    requireAuth: boolean,
}

const defaultSettings: SettingsType = {
  url: 'https://ux4.edvschule-plattling.de/klatab/',
  username: '',
  password: '',
  systemTheme: true,
  darkTheme: false,
  requireAuth: true,
};

const SettingsProvider = ({ children }) => {
  const [settings, setSettings] = useState(defaultSettings);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadSettings = async () => {
      try {
        const storedSettings = await AsyncStorage.getItem('appSettings');
        if (storedSettings) {
          setSettings(JSON.parse(storedSettings));
        }
      } catch (error) {
        console.error('Error loading settings:', error);
        Alert.alert('Fehler', 'Einstellungen konnten nicht geladen werden!');
        setSettings(defaultSettings);
      }finally{
        setLoading(false)
      }
    };

    loadSettings();
  }, []);

  const updateSettings = async (newSettings: SettingsType) => {
    try {
      await AsyncStorage.setItem('appSettings', JSON.stringify(newSettings));
      setSettings(newSettings);
    } catch (error) {
      console.error('Error updating settings:', error);
    }
  };

  const renderContent = () => {
    if (!loading) return (children)
  }

  return (
    <SettingsContext.Provider value={{ settings, updateSettings }}>
      {renderContent()}
    </SettingsContext.Provider>
  );
};

export default SettingsProvider;
