import React, { useEffect, useState } from "react";
import { ActivityIndicator, Alert, Pressable, ScrollView, Text, TextInput, View, } from "react-native";
import { withClickTracking } from "../../services/telemetry";
import { SafeAreaView } from "react-native-safe-area-context";
import { useNavigation } from "../../context/NavigationContext";
import { StatusBar } from "expo-status-bar";
import { Ionicons } from "@expo/vector-icons";
import { useColorScheme } from "nativewind";
import * as Haptics from "expo-haptics";
import AuthService from "../../services/auth.service";
import { getDefaultBaseUrl } from "../../services/api-config";
import { useAppConfig } from "../../context/AppConfigContext";
import { getErrorMessage } from "../../utils/error";
export function ServerConfigScreen({ healthCheckPath = "/api/health", helpBullets, defaultMaxRetries = 3, defaultTimeoutSeconds = 30, } = {}) {
    const router = useNavigation();
    const { appName } = useAppConfig();
    const defaultUrl = getDefaultBaseUrl();
    const [serverUrl, setServerUrl] = useState("");
    const [isTestingConnection, setIsTestingConnection] = useState(false);
    const [connectionStatus, setConnectionStatus] = useState("idle");
    const [testAttempt, setTestAttempt] = useState(0);
    const [isLoading, setIsLoading] = useState(true);
    const { colorScheme } = useColorScheme();
    const isDark = colorScheme === "dark";
    useEffect(() => {
        try {
            setServerUrl(AuthService.getBaseUrl());
        }
        catch {
            setServerUrl(defaultUrl);
        }
        finally {
            setIsLoading(false);
        }
    }, [defaultUrl]);
    const testConnectionWithRetry = async (url, attemptNumber = 1) => {
        const timeoutMs = defaultTimeoutSeconds * 1000;
        try {
            setTestAttempt(attemptNumber);
            const formattedUrl = url.endsWith("/") ? url.slice(0, -1) : url;
            const healthUrl = `${formattedUrl}${healthCheckPath}`;
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
            const response = await fetch(healthUrl, {
                method: "GET",
                signal: controller.signal,
                headers: { Accept: "application/json" },
            });
            clearTimeout(timeoutId);
            if (response.ok) {
                const data = await response.json();
                if (data.status === "healthy" && data.version) {
                    return true;
                }
            }
            if (attemptNumber < defaultMaxRetries) {
                await new Promise((resolve) => setTimeout(resolve, attemptNumber * 1000));
                return await testConnectionWithRetry(url, attemptNumber + 1);
            }
            return false;
        }
        catch {
            if (attemptNumber < defaultMaxRetries) {
                await new Promise((resolve) => setTimeout(resolve, attemptNumber * 1000));
                return await testConnectionWithRetry(url, attemptNumber + 1);
            }
            return false;
        }
    };
    const testConnection = async () => {
        if (!serverUrl) {
            Alert.alert("Error", "Please enter a server URL");
            return;
        }
        setIsTestingConnection(true);
        setConnectionStatus("testing");
        setTestAttempt(0);
        Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
        try {
            const success = await testConnectionWithRetry(serverUrl);
            setIsTestingConnection(false);
            if (success) {
                setConnectionStatus("success");
                Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
                Alert.alert("Success", "Connection successful! Server is reachable and responding correctly.", [{ text: "OK" }]);
            }
            else {
                setConnectionStatus("error");
                Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);
                Alert.alert("Connection Failed", `Unable to reach the server after ${defaultMaxRetries} attempts. Please check the URL and try again.`, [{ text: "OK" }]);
            }
        }
        catch {
            setIsTestingConnection(false);
            setConnectionStatus("error");
            Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);
            Alert.alert("Connection Error", "An unexpected error occurred while testing the connection.", [{ text: "OK" }]);
        }
    };
    const handleSave = async () => {
        if (!serverUrl) {
            Alert.alert("Error", "Please enter a server URL");
            return;
        }
        const sanitizedUrl = serverUrl.trim();
        try {
            const url = new URL(sanitizedUrl);
            if (url.protocol === "http:" && !["localhost", "127.0.0.1"].includes(url.hostname)) {
                Alert.alert("HTTPS Required", "Non-localhost connections require HTTPS. Please use an https:// URL.", [{ text: "OK" }]);
                return;
            }
        }
        catch {
            // setBaseUrl validates and surfaces the error
        }
        try {
            await AuthService.setBaseUrl(sanitizedUrl);
            Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
            Alert.alert("Configuration Saved", "Server settings have been saved.", [
                { text: "OK", onPress: () => router.back() },
            ]);
        }
        catch (e) {
            Alert.alert("Save Failed", `Unable to save the configuration: ${getErrorMessage(e)}`, [
                { text: "OK" },
            ]);
        }
    };
    const handleUseDefault = () => {
        setServerUrl(defaultUrl);
        setConnectionStatus("idle");
        Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
    };
    const handleClearConfiguration = () => {
        Alert.alert("Clear Configuration", "This will reset all server settings to defaults. Are you sure?", [
            { text: "Cancel", style: "cancel" },
            {
                text: "Clear",
                style: "destructive",
                onPress: async () => {
                    try {
                        await AuthService.resetBaseUrl();
                        setServerUrl(defaultUrl);
                        setConnectionStatus("idle");
                        Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
                        Alert.alert("Success", "Configuration has been reset to defaults.");
                    }
                    catch {
                        Alert.alert("Error", "Failed to clear configuration.");
                    }
                },
            },
        ]);
    };
    if (isLoading) {
        return (<SafeAreaView className="flex-1 bg-background dark:bg-black">
        <View className="flex-1 items-center justify-center">
          <ActivityIndicator size="large" color={isDark ? "white" : "black"}/>
        </View>
      </SafeAreaView>);
    }
    const bullets = helpBullets ?? [
        `Default server is hosted at ${defaultUrl}`,
        "Ensure your server is running and the /api/health endpoint is accessible",
        "Use HTTPS for secure connections",
    ];
    return (<SafeAreaView className="flex-1 bg-background dark:bg-black">
      <StatusBar style="auto"/>
      <ScrollView className="flex-1">
        <View className="px-6 py-6">
          <View className="mb-8 flex-row items-center justify-between">
            <Pressable onPress={withClickTracking("auth.server_config.back", () => router.back())} accessibilityRole="button" accessibilityLabel="Go back" className="active:scale-98 h-10 w-10 items-center justify-center rounded-lg bg-secondary dark:bg-neutral-800">
              <Ionicons name="close" size={24} color={isDark ? "white" : "black"}/>
            </Pressable>
            <Text className="text-lg font-semibold text-foreground dark:text-white">
              Server Configuration
            </Text>
            <View className="h-10 w-10"/>
          </View>

          <View className="mb-6 rounded-lg bg-secondary dark:bg-neutral-800 p-4">
            <View className="flex-row items-start">
              <Ionicons name="information-circle" size={24} color={isDark ? "#3b82f6" : "#2563eb"}/>
              <View className="ml-3 flex-1">
                <Text className="mb-1 text-sm font-semibold text-foreground dark:text-white">
                  Self-Hosted Server
                </Text>
                <Text className="text-xs text-muted-foreground dark:text-neutral-400">
                  Configure your own {appName} server for complete control over your data. Default
                  server: {defaultUrl}
                </Text>
              </View>
            </View>
          </View>

          <View className="mb-6">
            <Text className="mb-2 text-sm font-medium text-foreground dark:text-white">
              Server URL
            </Text>
            <View className="flex-row items-center rounded-lg border border-border dark:border-neutral-800 bg-background dark:bg-black px-3 py-3">
              <Ionicons name="globe-outline" size={20} color={isDark ? "rgba(255, 255, 255, 0.5)" : "rgba(0, 0, 0, 0.5)"}/>
              <TextInput value={serverUrl} onChangeText={(text) => {
            setServerUrl(text);
            setConnectionStatus("idle");
        }} placeholder={defaultUrl} placeholderTextColor={isDark ? "rgba(255, 255, 255, 0.5)" : "rgba(0, 0, 0, 0.5)"} autoCapitalize="none" autoCorrect={false} keyboardType="url" accessibilityLabel="Server URL" className="ml-2 flex-1 text-base text-foreground dark:text-white"/>
              {connectionStatus === "success" && (<Ionicons name="checkmark-circle" size={20} color="#22c55e"/>)}
              {connectionStatus === "error" && (<Ionicons name="close-circle" size={20} color="#ef4444"/>)}
            </View>
          </View>

          <Pressable onPress={withClickTracking("auth.server_config.test_connection", testConnection)} disabled={isTestingConnection} accessibilityRole="button" accessibilityLabel="Test connection" className="active:scale-98 mb-3 w-full rounded-lg border border-border dark:border-neutral-800 bg-background dark:bg-black px-6 py-4">
            {isTestingConnection ? (<View className="flex-row items-center justify-center">
                <ActivityIndicator size="small" color={isDark ? "white" : "black"}/>
                <Text className="ml-2 text-base font-semibold text-foreground dark:text-white">
                  Testing Connection
                  {testAttempt > 0 ? ` (Attempt ${testAttempt}/${defaultMaxRetries})` : "..."}
                </Text>
              </View>) : (<View className="flex-row items-center justify-center">
                <Ionicons name="wifi-outline" size={20} color={isDark ? "white" : "black"}/>
                <Text className="ml-2 text-base font-semibold text-foreground dark:text-white">
                  Test Connection
                </Text>
              </View>)}
          </Pressable>

          <Pressable onPress={withClickTracking("auth.server_config.use_default", handleUseDefault)} accessibilityRole="button" accessibilityLabel="Use default server" className="active:scale-98 mb-3 w-full rounded-lg border border-border dark:border-neutral-800 bg-background dark:bg-black px-6 py-4">
            <View className="flex-row items-center justify-center">
              <Ionicons name="cloud-outline" size={20} color={isDark ? "white" : "black"}/>
              <Text className="ml-2 text-base font-semibold text-foreground dark:text-white">
                Use Default Server
              </Text>
            </View>
          </Pressable>

          <Pressable onPress={withClickTracking("auth.server_config.clear_configuration", handleClearConfiguration)} accessibilityRole="button" accessibilityLabel="Clear all settings" className="active:scale-98 mb-3 w-full rounded-lg border border-destructive dark:border-red-900 bg-background dark:bg-black px-6 py-3">
            <View className="flex-row items-center justify-center">
              <Ionicons name="trash-outline" size={20} color="#ef4444"/>
              <Text className="ml-2 text-base font-medium text-destructive dark:text-red-900">
                Clear All Settings
              </Text>
            </View>
          </Pressable>

          <Pressable onPress={withClickTracking("auth.server_config.save", handleSave)} accessibilityRole="button" accessibilityLabel="Save configuration" className="active:scale-98 mb-6 w-full rounded-lg bg-primary dark:bg-white px-6 py-4">
            <Text className="text-center text-base font-semibold text-primary-foreground dark:text-black">
              Save Configuration
            </Text>
          </Pressable>

          <View className="rounded-lg bg-card dark:bg-neutral-900/50 p-4">
            <Text className="mb-3 text-sm font-semibold text-foreground dark:text-white">
              Need Help?
            </Text>
            <View className="space-y-2">
              {bullets.map((bullet, idx) => (<View key={idx} className="flex-row items-start">
                  <Text className="mr-2 text-sm text-muted-foreground dark:text-neutral-400">
                    •
                  </Text>
                  <Text className="flex-1 text-sm text-muted-foreground dark:text-neutral-400">
                    {bullet}
                  </Text>
                </View>))}
            </View>
          </View>
        </View>
      </ScrollView>
    </SafeAreaView>);
}
export default ServerConfigScreen;
//# sourceMappingURL=ServerConfigScreen.jsx.map