import React, { useEffect, useState } from "react";
import { StyleSheet, View } from "react-native";
import { NavigationContainer } from "@react-navigation/native";

import {
  default as ReactNativeSettings,
  SettingsElement,
} from "@mmomtchev/react-native-settings";
import { longLang } from "@/app/i18n/lang";
import { Translator, language_matrix } from "@/app/i18n/api";

// We will store the config here
const configData: Record<string, string> = {};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    justifyContent: "center",
    padding: "1.5%",
  },
});

// Retrieve a conf item or return the default
const confGet = (key: string, def: string): string => configData[key] || def;

// Store a conf item
const confSet = (key: string, value: string): void => {
  configData[key] = value;
};

// Choose from a list item
const intelligence: Record<string, string> = {
  L: "Low",
  M: "Medium",
  H: "High",
};


export default function Settings() {
  // Simply pass the schema here
  // It integrates in your existing `NavigationContainer` or `Screen`
  const [translator, setTranslator] = useState<Translator>(new Translator("en"))
  const [languages, setLanguages] = useState<language_matrix | undefined>();
  const [languagesLoaded, setLanguagesLoaded] = useState<boolean>(false);


  // This is the configuration schema
  const settings: SettingsElement[] = [
    {
      label: "LibreTranslate server",
      type: "string",
      get: confGet.bind(null, "@ltServer", "http://localhost:5000"),
      set: confSet.bind(null, "@ltServer"),
    },
    {
      label: "Host Language",
      type: "enum",
      // You can override the way the value is displayed
      values: ["en", "es", "fr"],
      display: (v : string) => {
        return longLang(v);
      },
      get: confGet.bind(null, "@hostLanguage", ""),
      set: confSet.bind(null, "@hostLanguage"),
    },
  ];

  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);
      }
    };
  });

  return (
    <NavigationContainer>
      <View style={styles.container}>
        <ReactNativeSettings settings={settings} />
      </View>
    </NavigationContainer>
  );
}
