import React, { useState, useEffect } from "react";
import { View, Text, TextInput, StyleSheet } from "react-native";
import { Settings } from "@/app/lib/settings";
import { Picker } from "@react-native-picker/picker";
import {
  LanguageServer,
  language_matrix,
} from "@/app/i18n/api";

const LIBRETRANSLATE_BASE_URL = "https://translate.argosopentech.com/translate";

const SettingsComponent = () => {
  const [hostLanguage, setHostLanguage] = useState<string | null>(null);
  const [libretranslateBaseUrl, setLibretranslateBaseUrl] = useState<
    string | null
  >(null);
  const [languageOptions, setLanguageOptions] = useState<
    language_matrix | undefined
  >();
  const [langServerConn, setLangServerConn] = useState<{
    success: boolean;
    error?: string;
  } | null>(null);

  useEffect(() => {
    (async function () {
      const settings = await Settings.getDefault();
      setHostLanguage((await settings.getHostLanguage()) || "en");
      setLibretranslateBaseUrl(
        (await settings.getLibretranslateBaseUrl()) || LIBRETRANSLATE_BASE_URL
      );
    })();
  });


  const handleHostLanguageChange = async (lang: string) => {
    const settings = await Settings.getDefault();
    setHostLanguage(lang);
    await settings.setHostLanguage(lang);
  };

  const handleLibretranslateBaseUrlChange = async (url: string) => {
    const settings = await Settings.getDefault();
    setLibretranslateBaseUrl(url);
    await settings.setLibretranslateBaseUrl(url);
    checkLangServerConnection(url);
  };

  const checkLangServerConnection = async (baseUrl: string) => {
    try {
      // Replace with actual connection check logic
      const testResult = await fetch(baseUrl, {
        method: "HEAD",
      });
      if (testResult.status !== 200) {
        setLangServerConn({ success: true, error: testResult.statusText });
      }
    } catch (error) {
      setLangServerConn({ success: false, error: `${error}` });
    }
  };

  return hostLanguage && libretranslateBaseUrl ? (
    <View style={styles.container}>
      <Text style={styles.label}>Host Language:</Text>
      {
        <Picker
          selectedValue={hostLanguage}
          style={{ height: 50, width: "100%" }}
          onValueChange={handleHostLanguageChange}
          accessibilityHint="host language"
        >
          {languageOptions &&
            Object.entries(languageOptions).map(([key, value]) => {
              return <Picker.Item label={value.name} value={value.code} />;
            })}
        </Picker>
      }

      <Text style={styles.label}>LibreTranslate Base URL:</Text>
      <TextInput
        style={styles.input}
        value={libretranslateBaseUrl || LIBRETRANSLATE_BASE_URL}
        onChangeText={handleLibretranslateBaseUrlChange}
        accessibilityHint="libretranslate base url"
      />
      {langServerConn &&
        (langServerConn.success ? (
          <Text>Success connecting to {libretranslateBaseUrl}</Text>
        ) : (
          <Text>
            Error connecting to {libretranslateBaseUrl}: {langServerConn.error}
          </Text>
        ))}
    </View>
  ) : (
    <View>
      <Text>Loading ...</Text>
    </View>
  );
};

// Create styles for the component
const styles = StyleSheet.create({
  downloadButtonWrapper: {
    flexDirection: "row",
  },
  downloadButton: {
    backgroundColor: "#236b9f",
    padding: 20,
    margin: 10,
    flex: 1,
    flexDirection: "column",
    alignItems: "center",
  },
  deleteButton: {
    backgroundColor: "darkred",
    flex: 1,
    flexDirection: "column",
    padding: 10,
    margin: 10,
    height: 50,
  },
  pauseDownloadButton: {
    backgroundColor: "#444444",
    padding: 10,
    margin: 10,
    height: 50,
  },
  buttonText: {
    color: "#fff",
    // flex: 1,
    // fontSize: 16,
    // alignSelf: "center",
    // textAlign: "center",
    // textAlignVertical: "top",
  },
  container: {
    flex: 1,
    padding: 20,
  },
  label: {
    fontSize: 16,
    marginBottom: 8,
  },
  input: {
    height: 40,
    borderColor: "gray",
    borderWidth: 1,
    marginBottom: 20,
    paddingHorizontal: 8,
  },
});

export default SettingsComponent;
