import React, { useState } from "react";
import { View, Text, TextInput, StyleSheet, KeyboardAvoidingView, Platform, ScrollView, Alert, TouchableOpacity } 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 LoginScreen() {
  const { signIn } = useAuth();
  const nav = useNavigation<any>();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [busy, setBusy] = useState(false);

  const onSubmit = async () => {
    if (!email || !password) return;
    setBusy(true);
    try { await signIn(email.trim(), password); }
    catch (e: any) { Alert.alert("Sign in failed", String(e?.message ?? e)); }
    finally { setBusy(false); }
  };

  return (
    <KeyboardAvoidingView behavior={Platform.OS === "ios" ? "padding" : undefined} style={styles.wrap}>
      <ScrollView contentContainerStyle={styles.scroll} keyboardShouldPersistTaps="handled">
        <View style={styles.brand}>
          <Text style={styles.brandMark}>◆</Text>
          <H1 style={{ marginTop: spacing.sm }}>Delta Terminal</H1>
          <Muted>Realtime multi-coin trading terminal</Muted>
        </View>
        <Card>
          <Text style={styles.label}>Email</Text>
          <TextInput
            style={styles.input} value={email} onChangeText={setEmail}
            autoCapitalize="none" keyboardType="email-address"
            placeholder="you@example.com" placeholderTextColor={colors.textDim}
          />
          <Text style={styles.label}>Password</Text>
          <TextInput
            style={styles.input} value={password} onChangeText={setPassword}
            secureTextEntry placeholder="••••••••" placeholderTextColor={colors.textDim}
          />
          <View style={{ height: spacing.md }} />
          <PrimaryButton label={busy ? "Signing in…" : "Sign in"} onPress={onSubmit} disabled={busy} />
          <TouchableOpacity onPress={() => nav.navigate("Register")} style={{ marginTop: spacing.md, alignItems: "center" }}>
            <Muted>Don't have an account? Create one</Muted>
          </TouchableOpacity>
        </Card>
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  wrap: { flex: 1, backgroundColor: colors.bg },
  scroll: { flexGrow: 1, justifyContent: "center", padding: spacing.lg },
  brand: { alignItems: "center", marginBottom: spacing.xl },
  brandMark: { fontSize: 44, color: colors.primary },
  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,
  },
});
