import { useState } from "react";
import { View, Text, TextInput, Pressable } from "react-native";
import { api } from "../../lib/api";
import { setToken } from "../../lib/auth";
import { useRouter } from "expo-router";
import { registerForPushAndSendToServer } from "../../lib/push";

export default function Login() {
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [password, setPassword] = useState("");
  const [msg, setMsg] = useState("");
  const router = useRouter();

  async function login() {
    setMsg("Logging in...");
    const res = await api<any>("/auth/login", {
      method: "POST",
      body: JSON.stringify({ email: email || undefined, phone: phone || undefined, password }),
    });
    await setToken(res.accessToken);
    await registerForPushAndSendToServer();
    setMsg("");
    router.replace("/(client)");
  }

  async function register() {
    setMsg("Registering...");
    const res = await api<any>("/auth/register", {
      method: "POST",
      body: JSON.stringify({ email: email || undefined, phone: phone || undefined, password, displayName: "User" }),
    });
    await setToken(res.accessToken);
    await registerForPushAndSendToServer();
    setMsg("");
    router.replace("/(client)");
  }

  return (
    <View style={{ padding: 16, gap: 10 }}>
      <Text style={{ fontSize: 18, fontWeight: "700" }}>Login / Register</Text>

      <TextInput value={email} onChangeText={setEmail} placeholder="Email (optional)"
        style={{ borderWidth: 1, borderRadius: 10, padding: 12 }} autoCapitalize="none" />

      <TextInput value={phone} onChangeText={setPhone} placeholder="Phone (optional)"
        style={{ borderWidth: 1, borderRadius: 10, padding: 12 }} autoCapitalize="none" />

      <TextInput value={password} onChangeText={setPassword} placeholder="Password" secureTextEntry
        style={{ borderWidth: 1, borderRadius: 10, padding: 12 }} />

      <View style={{ flexDirection: "row", gap: 10 }}>
        <Pressable onPress={login} style={{ backgroundColor: "black", padding: 12, borderRadius: 10, flex: 1 }}>
          <Text style={{ color: "white", textAlign: "center" }}>Login</Text>
        </Pressable>
        <Pressable onPress={register} style={{ borderWidth: 1, padding: 12, borderRadius: 10, flex: 1 }}>
          <Text style={{ textAlign: "center" }}>Register</Text>
        </Pressable>
      </View>

      {!!msg && <Text style={{ opacity: 0.7 }}>{msg}</Text>}
    </View>
  );
}
