import React, { useState } from "react";
import { View, TextInput, StyleSheet, ScrollView, Alert, TouchableOpacity, Text } from "react-native";
import { useAuth } from "@/auth/AuthProvider";
import { PrimaryButton, Card, H1, Muted } from "@/components/ui";
import { colors, spacing, radii } from "@/theme";
import { useNavigation } from "@react-navigation/native";

export default function RegisterScreen() {
  const { register } = useAuth();
  const nav = useNavigation<any>();
  const [f, setF] = useState({ first_name: "", last_name: "", email: "", password: "" });
  const [busy, setBusy] = useState(false);

  const onSubmit = async () => {
    if (f.password.length < 8) { Alert.alert("Password", "Minimum 8 characters."); return; }
    setBusy(true);
    try { await register({ ...f, email: f.email.trim() }); }
    catch (e: any) { Alert.alert("Register failed", String(e?.message ?? e)); }
    finally { setBusy(false); }
  };

  return (
    <ScrollView contentContainerStyle={styles.scroll} style={{ backgroundColor: colors.bg }}>
      <View style={{ alignItems: "center", marginBottom: spacing.xl }}>
        <H1>Create account</H1>
        <Muted>Sign up to start trading</Muted>
      </View>
      <Card>
        {(["first_name", "last_name", "email", "password"] as const).map((k) => (
          <View key={k}>
            <Text style={styles.label}>{k.replace("_", " ")}</Text>
            <TextInput
              style={styles.input}
              value={f[k]} onChangeText={(v) => setF((p) => ({ ...p, [k]: v }))}
              autoCapitalize={k === "email" ? "none" : "words"}
              keyboardType={k === "email" ? "email-address" : "default"}
              secureTextEntry={k === "password"}
              placeholderTextColor={colors.textDim}
            />
          </View>
        ))}
        <View style={{ height: spacing.md }} />
        <PrimaryButton label={busy ? "Creating…" : "Create account"} onPress={onSubmit} disabled={busy} />
        <TouchableOpacity onPress={() => nav.goBack()} style={{ marginTop: spacing.md, alignItems: "center" }}>
          <Muted>Already have an account? Sign in</Muted>
        </TouchableOpacity>
      </Card>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  scroll: { flexGrow: 1, justifyContent: "center", padding: spacing.lg },
  label: { color: colors.textMuted, fontSize: 11, textTransform: "uppercase", letterSpacing: 0.6, marginTop: spacing.sm, marginBottom: 4 },
  input: {
    backgroundColor: colors.bg, color: colors.text,
    borderColor: colors.border, borderWidth: 1, borderRadius: radii.md,
    paddingHorizontal: spacing.md, paddingVertical: 10, fontSize: 15,
  },
});
