import { useRouter } from "expo-router";
import { useEffect, useState } from "react";
import { ScrollView, Text } from "react-native";
import { Button, Field } from "../components/ui";
import { api } from "../lib/api";
import { DEFAULT_URL, getConfig, setConfig } from "../lib/config";
import { sync } from "../lib/store";
import { C } from "../lib/theme";

export default function Settings() {
  const router = useRouter();
  const [url, setUrl] = useState(DEFAULT_URL);
  const [token, setToken] = useState("");
  const [status, setStatus] = useState<string | null>(null);

  useEffect(() => {
    getConfig().then((c) => {
      setUrl(c.url);
      setToken(c.token);
    });
  }, []);

  const save = async () => {
    await setConfig(url, token);
    try {
      await api.tasks.list({ status: "inbox" });
      void sync();
      router.back();
    } catch (e) {
      setStatus(`Connection failed: ${e instanceof Error ? e.message : e}`);
    }
  };

  return (
    <ScrollView style={{ flex: 1, backgroundColor: C.bg }} contentContainerStyle={{ padding: 16 }}>
      <Field label="Server" value={url} onChangeText={setUrl} autoCapitalize="none" autoCorrect={false} />
      <Field
        label="API token"
        value={token}
        onChangeText={setToken}
        autoCapitalize="none"
        autoCorrect={false}
        secureTextEntry
      />
      <Button title="Save & test" onPress={save} />
      {status && <Text style={{ color: C.danger }}>{status}</Text>}
    </ScrollView>
  );
}
