import React, { useContext, useState } from "react";
import { TextInput, Button, Text } from "react-native";
import ScreenLayout from "../components/layout/ScreenLayout";
import { AuthContext } from "../context/AuthContext";
import { registerApi } from "../api";

export default function RegisterScreen() {
  const { login } = useContext(AuthContext);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");

  const handleRegister = async () => {
    try {
      setError("");
      const token = await registerApi(email, password);
      await login(token);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Registration failed");
    }
  };

  return (
    <ScreenLayout>
      <TextInput
        placeholder="Email"
        value={email}
        onChangeText={setEmail}
        autoCapitalize="none"
        autoCorrect={false}
        keyboardType="email-address"
        placeholderTextColor="#888"
        style={{
          borderWidth: 1,
          borderColor: "#ccc",
          borderRadius: 8,
          paddingHorizontal: 12,
          paddingVertical: 10,
          color: "#111",
          marginBottom: 12,
        }}
      />
      <TextInput
        placeholder="Password"
        value={password}
        onChangeText={setPassword}
        secureTextEntry
        placeholderTextColor="#888"
        style={{
          borderWidth: 1,
          borderColor: "#ccc",
          borderRadius: 8,
          paddingHorizontal: 12,
          paddingVertical: 10,
          color: "#111",
          marginBottom: 12,
        }}
      />
      {!!error && <Text style={{ color: "red", marginBottom: 8 }}>{error}</Text>}
      <Button title="Register" onPress={() => void handleRegister()} />
    </ScreenLayout>
  );
}
