import React, { useState } from 'react';
import {
  KeyboardAvoidingView, Platform, Pressable, StyleSheet, Text, TextInput, View,
} from 'react-native';
import { useAuth } from '../lib/api';
import { C } from '../lib/theme';

export function LoginScreen() {
  const { login } = useAuth();
  const [user, setUser] = useState('admin');
  const [pass, setPass] = useState('');
  const [err, setErr] = useState('');
  const [busy, setBusy] = useState(false);

  const go = async () => {
    setBusy(true);
    setErr('');
    try {
      const ok = await login(user.trim(), pass);
      if (!ok) setErr('Wrong password.');
      else setPass('');
    } catch {
      setErr('Network error — are you online?');
    } finally {
      setBusy(false);
    }
  };

  return (
    <KeyboardAvoidingView
      style={s.wrap}
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}>
      <View style={s.card}>
        <Text style={{ fontSize: 34, marginBottom: 10 }}>⚕️</Text>
        <Text style={s.h1}>Health Dashboard</Text>
        <Text style={s.sub}>health.rehbock.xyz — private</Text>
        <Text style={s.lbl}>USER</Text>
        <TextInput
          style={s.input}
          value={user}
          onChangeText={setUser}
          autoCapitalize="none"
          autoCorrect={false}
          textContentType="username"
        />
        <Text style={s.lbl}>PASSWORD</Text>
        <TextInput
          style={s.input}
          value={pass}
          onChangeText={setPass}
          secureTextEntry
          textContentType="password"
          onSubmitEditing={go}
          returnKeyType="go"
        />
        <Pressable style={[s.go, busy && { opacity: 0.5 }]} disabled={busy} onPress={go}>
          <Text style={{ color: '#fff', fontWeight: '600', fontSize: 15 }}>Unlock</Text>
        </Pressable>
        <Text style={s.err}>{err}</Text>
      </View>
    </KeyboardAvoidingView>
  );
}

const s = StyleSheet.create({
  wrap: {
    flex: 1, backgroundColor: C.bg, alignItems: 'center', justifyContent: 'center', padding: 24,
  },
  card: {
    width: '100%', maxWidth: 340, backgroundColor: C.surface, borderWidth: 1,
    borderColor: C.border, borderRadius: 16, paddingVertical: 28, paddingHorizontal: 24,
  },
  h1: { fontSize: 18, fontWeight: '600', color: C.text, marginBottom: 4 },
  sub: { fontSize: 12, color: C.muted, marginBottom: 20 },
  lbl: { fontSize: 11, color: C.muted, letterSpacing: 0.5, marginTop: 12, marginBottom: 5 },
  input: {
    paddingVertical: 11, paddingHorizontal: 12, borderRadius: 10, borderWidth: 1,
    borderColor: C.border, backgroundColor: C.surface2, color: C.text, fontSize: 15,
  },
  go: {
    marginTop: 20, padding: 12, borderRadius: 10, backgroundColor: C.accent, alignItems: 'center',
  },
  err: { marginTop: 12, fontSize: 12.5, color: C.red, minHeight: 18 },
});
