/**
 * LoginScreen.tsx — first-run auth config. The engineer enters their extension
 * profile once; it's persisted (authStore) so future launches + push wakeups are
 * silent. Clean, single-column form with validation and a busy state.
 */
import React, { useState } from 'react';
import {
  View, Text, TextInput, Pressable, StyleSheet, ScrollView,
  KeyboardAvoidingView, Platform, ActivityIndicator, Alert,
} from 'react-native';
import { colors, spacing, radius, typography } from '../theme';
import { loginDirect } from '../services/authStore';
import { SipConfig } from '../config';

interface Props {
  onLoggedIn: (cfg: SipConfig) => void;
}

export default function LoginScreen({ onLoggedIn }: Props) {
  const [wsServer, setWsServer] = useState('wss://go.mindserv.co:8089/ws');
  const [domain, setDomain] = useState('go.mindserv.co');
  const [extension, setExtension] = useState('');
  const [password, setPassword] = useState('');
  const [displayName, setDisplayName] = useState('');
  const [busy, setBusy] = useState(false);

  const canSubmit = wsServer && domain && extension && password && !busy;

  const submit = async () => {
    if (!canSubmit) return;
    setBusy(true);
    try {
      const cfg = await loginDirect({ wsServer, domain, extension, password, displayName });
      onLoggedIn(cfg);
    } catch (e: any) {
      Alert.alert('Sign in failed', e?.message || 'Check your details and try again.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <KeyboardAvoidingView
      style={styles.flex}
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
    >
      <ScrollView contentContainerStyle={styles.container} keyboardShouldPersistTaps="handled">
        <View style={styles.logo}>
          <Text style={styles.logoMark}>📞</Text>
        </View>
        <Text style={styles.title}>ePhone</Text>
        <Text style={styles.subtitle}>Sign in to your field line</Text>

        <Field label="Extension (your agent id)" value={extension} onChange={setExtension}
          placeholder="agent2" autoCapitalize="none" />
        <Field label="Password" value={password} onChange={setPassword}
          placeholder="Your SIP secret (e.g. agent2pass)" secureTextEntry />
        <Field label="Display name" value={displayName} onChange={setDisplayName}
          placeholder="Arun Field" />

        <Text style={styles.sectionLabel}>SERVER</Text>
        <Field label="WSS server" value={wsServer} onChange={setWsServer}
          autoCapitalize="none" />
        <Field label="SIP domain" value={domain} onChange={setDomain}
          autoCapitalize="none" />

        <Pressable
          onPress={submit}
          disabled={!canSubmit}
          style={[styles.cta, !canSubmit && styles.ctaDisabled]}
        >
          {busy ? (
            <ActivityIndicator color={colors.white} />
          ) : (
            <Text style={styles.ctaText}>Sign In</Text>
          )}
        </Pressable>

        <Text style={styles.hint}>
          Your profile is stored securely so incoming calls can wake the app while
          it's in your pocket.
        </Text>
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

function Field(props: {
  label: string; value: string; onChange: (v: string) => void;
  placeholder?: string; secureTextEntry?: boolean; keyboardType?: any; autoCapitalize?: any;
}) {
  return (
    <View style={styles.field}>
      <Text style={styles.fieldLabel}>{props.label}</Text>
      <TextInput
        value={props.value}
        onChangeText={props.onChange}
        placeholder={props.placeholder}
        placeholderTextColor={colors.textSecondary}
        secureTextEntry={props.secureTextEntry}
        keyboardType={props.keyboardType}
        autoCapitalize={props.autoCapitalize ?? 'words'}
        autoCorrect={false}
        style={styles.input}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  flex: { flex: 1, backgroundColor: colors.bg },
  container: { padding: spacing.lg, paddingTop: spacing.xxl, paddingBottom: spacing.xxl },
  logo: {
    alignSelf: 'center', width: 84, height: 84, borderRadius: 20,
    backgroundColor: colors.bgSecondary, alignItems: 'center', justifyContent: 'center',
    marginBottom: spacing.md,
  },
  logoMark: { fontSize: 44 },
  title: { ...typography.largeTitle, color: colors.text, textAlign: 'center' },
  subtitle: { ...typography.body, color: colors.textSecondary, textAlign: 'center', marginBottom: spacing.xl },
  sectionLabel: { ...typography.label, color: colors.textSecondary, marginTop: spacing.md, marginBottom: spacing.xs, marginLeft: spacing.xs },
  field: { marginBottom: spacing.md },
  fieldLabel: { ...typography.label, color: colors.textSecondary, marginBottom: spacing.xs, marginLeft: spacing.xs },
  input: {
    backgroundColor: colors.bgSecondary, borderRadius: radius.md,
    paddingHorizontal: spacing.md, paddingVertical: 14,
    fontSize: 17, color: colors.text,
  },
  cta: {
    backgroundColor: colors.primary, borderRadius: radius.md,
    paddingVertical: 16, alignItems: 'center', marginTop: spacing.lg,
  },
  ctaDisabled: { backgroundColor: colors.textSecondary, opacity: 0.5 },
  ctaText: { ...typography.button, color: colors.white },
  hint: { ...typography.label, color: colors.textSecondary, textAlign: 'center', marginTop: spacing.lg, lineHeight: 18 },
});
