import { CachedTranslator, Translator, language_matrix } from "@/app/i18n/api";
import { LIBRETRANSLATE_BASE_URL } from "@/constants/api";
import { Text } from "@react-navigation/elements";
import { useEffect, useState } from "react";
import ISpeakButton from "./ui/ISpeakButton";
import { LANG_FLAGS } from "@/app/i18n/lang";
import { ScrollView } from "react-native";
import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context";


export function LanguageSelection(props : {
    translator? : Translator
}) {
    const [languages, setLanguages] = useState<language_matrix|undefined>();
    const [languagesLoaded, setLanguagesLoaded] = useState<boolean>(false);

    const translator = props.translator || new CachedTranslator("en")

    useEffect(() => {
        const fetchData = async () => {
          try {
            // Replace with your actual async data fetching logic
            const languages = await translator.fetchLanguages();
            setLanguages(languages);
            setLanguagesLoaded(true);
          } catch (error) {
            console.error('Error fetching data:', error);
          }
        };
    
        fetchData();
      }, []);

    return (
        <ScrollView >
            <SafeAreaProvider >
                <SafeAreaView>
            {(languages && languagesLoaded) ? Object.entries(languages).filter((l) => (LANG_FLAGS as any)[l[0]] !== undefined).map(
                    ([lang, lang_entry]) => {
                        return (
                            <ISpeakButton language={lang_entry} key={lang_entry.code} />
                        );
                    }
                ) : <Text>Waiting...</Text>
            }
            </SafeAreaView>
            </SafeAreaProvider>
    </ScrollView>
)
}