/**
 * Quick add client — 10-second lead capture.
 * Name, phone, email. Source defaults to "Mobile App".
 */

import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  KeyboardAvoidingView,
  Platform,
  Alert,
  ScrollView,
} from 'react-native';
import type { NativeStackScreenProps } from '@react-navigation/native-stack';
import type { ClientsStackParamList } from '../../navigation/stacks/ClientsStack';
import { useTheme } from '../../themes/ThemeProvider';
import { createClient } from '../../services/api';

type Props = NativeStackScreenProps<ClientsStackParamList, 'AddClient'>;

export default function AddClient({ navigation }: Props) {
  const { theme } = useTheme();
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [source, setSource] = useState('Mobile App');
  const [notes, setNotes] = useState('');
  const [saving, setSaving] = useState(false);

  const handleSave = async () => {
    if (!firstName.trim()) {
      Alert.alert('Required', 'First name is required');
      return;
    }

    setSaving(true);
    const res = await createClient({
      first_name: firstName.trim(),
      last_name: lastName.trim(),
      email: email.trim() || undefined,
      phone: phone.trim() || undefined,
      source,
      notes: notes.trim() || undefined,
      lifecycle: 'lead',
    } as any);

    setSaving(false);

    if (res.success) {
      navigation.goBack();
    } else {
      Alert.alert('Error', res.error ?? 'Failed to save client');
    }
  };

  return (
    <KeyboardAvoidingView
      style={[styles.container, { backgroundColor: theme.colors.background }]}
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
    >
      <ScrollView contentContainerStyle={styles.form}>
        <View style={styles.row}>
          <View style={styles.half}>
            <Text style={[styles.label, { color: theme.colors.textSecondary }]}>First Name *</Text>
            <TextInput
              style={[styles.input, { color: theme.colors.text, backgroundColor: theme.colors.inputBg, borderColor: theme.colors.border }]}
              value={firstName}
              onChangeText={setFirstName}
              placeholder="First"
              placeholderTextColor={theme.colors.textSecondary}
              autoFocus
              autoCapitalize="words"
            />
          </View>
          <View style={styles.half}>
            <Text style={[styles.label, { color: theme.colors.textSecondary }]}>Last Name</Text>
            <TextInput
              style={[styles.input, { color: theme.colors.text, backgroundColor: theme.colors.inputBg, borderColor: theme.colors.border }]}
              value={lastName}
              onChangeText={setLastName}
              placeholder="Last"
              placeholderTextColor={theme.colors.textSecondary}
              autoCapitalize="words"
            />
          </View>
        </View>

        <Text style={[styles.label, { color: theme.colors.textSecondary }]}>Email</Text>
        <TextInput
          style={[styles.input, { color: theme.colors.text, backgroundColor: theme.colors.inputBg, borderColor: theme.colors.border }]}
          value={email}
          onChangeText={setEmail}
          placeholder="email@example.com"
          placeholderTextColor={theme.colors.textSecondary}
          keyboardType="email-address"
          autoCapitalize="none"
          autoCorrect={false}
        />

        <Text style={[styles.label, { color: theme.colors.textSecondary }]}>Phone</Text>
        <TextInput
          style={[styles.input, { color: theme.colors.text, backgroundColor: theme.colors.inputBg, borderColor: theme.colors.border }]}
          value={phone}
          onChangeText={setPhone}
          placeholder="(831) 555-0000"
          placeholderTextColor={theme.colors.textSecondary}
          keyboardType="phone-pad"
        />

        <Text style={[styles.label, { color: theme.colors.textSecondary }]}>Source</Text>
        <TextInput
          style={[styles.input, { color: theme.colors.text, backgroundColor: theme.colors.inputBg, borderColor: theme.colors.border }]}
          value={source}
          onChangeText={setSource}
          placeholder="Referral, Open House, etc."
          placeholderTextColor={theme.colors.textSecondary}
        />

        <Text style={[styles.label, { color: theme.colors.textSecondary }]}>Notes</Text>
        <TextInput
          style={[styles.input, styles.textArea, { color: theme.colors.text, backgroundColor: theme.colors.inputBg, borderColor: theme.colors.border }]}
          value={notes}
          onChangeText={setNotes}
          placeholder="Quick notes about this lead..."
          placeholderTextColor={theme.colors.textSecondary}
          multiline
          numberOfLines={3}
        />

        <TouchableOpacity
          style={[styles.saveBtn, { backgroundColor: theme.colors.primary, opacity: saving ? 0.6 : 1 }]}
          onPress={handleSave}
          disabled={saving}
        >
          <Text style={styles.saveBtnText}>{saving ? 'Saving...' : 'Save Client'}</Text>
        </TouchableOpacity>
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  form: { padding: 20 },
  row: { flexDirection: 'row', gap: 12 },
  half: { flex: 1 },
  label: {
    fontSize: 13,
    fontWeight: '600',
    marginBottom: 6,
    marginTop: 14,
  },
  input: {
    height: 44,
    borderRadius: 10,
    borderWidth: 1,
    paddingHorizontal: 14,
    fontSize: 15,
  },
  textArea: {
    height: 80,
    paddingTop: 10,
    textAlignVertical: 'top',
  },
  saveBtn: {
    height: 50,
    borderRadius: 12,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 24,
  },
  saveBtnText: {
    color: '#FFF',
    fontSize: 17,
    fontWeight: '700',
  },
});
