import { CachedTranslator, LanguageServer, Translator, language_matrix, language_matrix_entry } from "@/app/i18n/api";
import { LIBRETRANSLATE_BASE_URL } from "@/constants/api";
import { useEffect, useState } from "react";
import ISpeakButton from "./ui/ISpeakButton";
import { LANG_FLAGS } from "@/app/i18n/lang";
import { ScrollView, StyleSheet, Text, View } from "react-native";
import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context";
import { Conversation, Speaker } from "@/app/lib/conversation";
import { NavigationProp, ParamListBase } from "@react-navigation/native";
import { Link } from "expo-router";


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

  const languageServer = new LanguageServer(LIBRETRANSLATE_BASE_URL);
  const translator = props.translator || new CachedTranslator("en", undefined, languageServer);

  function onLangSelected(language: language_matrix_entry) {
    props.onLangSelected && props.onLangSelected(language)
  }


  useEffect(() => {
    const fetchData = async () => {
      try {
        // Replace with your actual async data fetching logic
        const languages = await languageServer.fetchLanguages();
        setLanguages(languages);
        setLanguagesLoaded(true);
      } catch (error) {
        error = error as Response;
        console.error('Error fetching data (%d %s): %s', (error as Response).status, (error as Response).statusText, (error as Response).body);
      }
    };

    fetchData();
  }, []);

  return (
    <View>
      <Link href={"/settings"}>
        <Text>Settings</Text>
      </Link>
      <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} onLangSelected={onLangSelected} />
                );
              }
            ) : <Text>Waiting...</Text>
            }
          </SafeAreaView>
        </SafeAreaProvider>
      </ScrollView>
    </View>
  )
}

const styles = StyleSheet.create({
  column: {
    flex: 1,
    flexDirection: 'row',
    flexWrap: 'wrap',
    padding: 8,
  },
})