import React, { useState } from "react";
import { View, Text, TextInput, TouchableOpacity, StyleSheet, Alert, KeyboardAvoidingView, Platform, ScrollView } from "react-native";
import { useRouter } from "expo-router";
import api from "../src/services/api";

export default function RegisterScreen(): React.ReactElement {
  const router = useRouter();
  const [form, setForm] = useState({ email: "", username: "", display_name: "", password: "", password_confirm: "" });
  const [loading, setLoading] = useState(false);

  const handleRegister = async (): Promise<void> => {
    if (form.password !== form.password_confirm) {
      Alert.alert("Error", "Passwords do not match.");
      return;
    }
    setLoading(true);
    try {
      await api.post("/auth/register/", form);
      Alert.alert("Success", "Account created. Please sign in.");
      router.replace("/login");
    } catch {
      Alert.alert("Error", "Registration failed. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <KeyboardAvoidingView style={styles.container} behavior={Platform.OS === "ios" ? "padding" : "height"}>
      <ScrollView contentContainerStyle={{ flexGrow: 1, justifyContent: "center" }}>
        <View style={styles.card}>
          <Text style={styles.title}>Create Account</Text>
          <Text style={styles.subtitle}>Join Cloud Reader</Text>

          {(["email", "username", "display_name", "password", "password_confirm"] as const).map((field) => (
            <View key={field}>
              <Text style={styles.label}>
                {field.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase())}
              </Text>
              <TextInput
                style={styles.input}
                value={form[field]}
                onChangeText={(val) => setForm((prev) => ({ ...prev, [field]: val }))}
                secureTextEntry={field.startsWith("password")}
                autoCapitalize={field === "email" ? "none" : "words"}
                placeholderTextColor="#8892a4"
              />
            </View>
          ))}

          <TouchableOpacity style={styles.button} onPress={handleRegister} disabled={loading}>
            <Text style={styles.buttonText}>{loading ? "Creating account..." : "Create Account"}</Text>
          </TouchableOpacity>

          <TouchableOpacity onPress={() => router.push("/login")}>
            <Text style={styles.link}>Already have an account? Sign In</Text>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: "#0f1419", padding: 24 },
  card: { width: "100%", maxWidth: 400, padding: 32, backgroundColor: "#1a1f2e", borderRadius: 12, alignSelf: "center" },
  title: { fontSize: 24, fontWeight: "700", color: "#e1e4ed", marginBottom: 4 },
  subtitle: { fontSize: 16, color: "#8892a4", marginBottom: 24 },
  label: { fontSize: 13, fontWeight: "500", color: "#8892a4", marginBottom: 6 },
  input: { backgroundColor: "#0f1419", borderWidth: 1, borderColor: "#2a3042", borderRadius: 8, padding: 12, color: "#e1e4ed", fontSize: 14, marginBottom: 16 },
  button: { backgroundColor: "#4f8cff", borderRadius: 8, padding: 14, alignItems: "center", marginTop: 8 },
  buttonText: { color: "#fff", fontWeight: "600", fontSize: 16 },
  link: { color: "#4f8cff", textAlign: "center", marginTop: 16, fontSize: 14 },
});