/**
 * Email compose — AI-assisted drafting with Fair Housing compliance.
 */

import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  Alert,
} from 'react-native';
import { useTheme } from '../../themes/ThemeProvider';
import { sendEmail, getAIDraft } from '../../services/api';

export default function Compose({ route, navigation }: any) {
  const { theme } = useTheme();
  const replyTo = route.params?.replyTo;
  const clientId = route.params?.clientId;

  const [to, setTo] = useState('');
  const [subject, setSubject] = useState(replyTo ? `Re: ` : '');
  const [body, setBody] = useState('');
  const [sending, setSending] = useState(false);
  const [aiLoading, setAiLoading] = useState(false);

  const handleSend = async () => {
    if (!to.trim()) {
      Alert.alert('Required', 'Recipient email is required');
      return;
    }
    setSending(true);
    const res = await sendEmail({
      to: to.trim(),
      subject: subject.trim(),
      body: body.trim(),
      client_id: clientId,
      thread_id: replyTo,
    });
    setSending(false);
    if (res.success) {
      navigation.goBack();
    } else {
      Alert.alert('Error', res.error ?? 'Failed to send');
    }
  };

  const handleAIDraft = async () => {
    setAiLoading(true);
    const res = await getAIDraft({
      to: to.trim(),
      subject: subject.trim(),
      context: body.trim(),
      client_id: clientId,
    });
    setAiLoading(false);
    if (res.success && res.data) {
      const draft = res.data as { body: string; subject?: string };
      setBody(draft.body ?? '');
      if (draft.subject && !subject) setSubject(draft.subject);
    } else {
      Alert.alert('AI Unavailable', res.error ?? 'Could not generate draft');
    }
  };

  return (
    <KeyboardAvoidingView
      style={[styles.container, { backgroundColor: theme.colors.background }]}
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
    >
      <ScrollView contentContainerStyle={styles.form}>
        <Text style={[styles.label, { color: theme.colors.textSecondary }]}>To</Text>
        <TextInput
          style={[styles.input, { color: theme.colors.text, backgroundColor: theme.colors.inputBg, borderColor: theme.colors.border }]}
          value={to}
          onChangeText={setTo}
          placeholder="recipient@email.com"
          placeholderTextColor={theme.colors.textSecondary}
          keyboardType="email-address"
          autoCapitalize="none"
          autoFocus
        />

        <Text style={[styles.label, { color: theme.colors.textSecondary }]}>Subject</Text>
        <TextInput
          style={[styles.input, { color: theme.colors.text, backgroundColor: theme.colors.inputBg, borderColor: theme.colors.border }]}
          value={subject}
          onChangeText={setSubject}
          placeholder="Subject"
          placeholderTextColor={theme.colors.textSecondary}
        />

        <View style={styles.bodyHeader}>
          <Text style={[styles.label, { color: theme.colors.textSecondary }]}>Message</Text>
          <TouchableOpacity
            style={[styles.aiBtn, { backgroundColor: theme.colors.accent, opacity: aiLoading ? 0.6 : 1 }]}
            onPress={handleAIDraft}
            disabled={aiLoading}
          >
            <Text style={styles.aiBtnText}>{aiLoading ? 'Drafting...' : '🤖 AI Draft'}</Text>
          </TouchableOpacity>
        </View>
        <TextInput
          style={[styles.textArea, { color: theme.colors.text, backgroundColor: theme.colors.inputBg, borderColor: theme.colors.border }]}
          value={body}
          onChangeText={setBody}
          placeholder="Type your message or use AI Draft..."
          placeholderTextColor={theme.colors.textSecondary}
          multiline
          textAlignVertical="top"
        />

        <Text style={[styles.compliance, { color: theme.colors.textSecondary }]}>
          All outbound emails are audited for Fair Housing compliance.
        </Text>

        <TouchableOpacity
          style={[styles.sendBtn, { backgroundColor: theme.colors.primary, opacity: sending ? 0.6 : 1 }]}
          onPress={handleSend}
          disabled={sending}
        >
          <Text style={styles.sendBtnText}>{sending ? 'Sending...' : 'Send Email'}</Text>
        </TouchableOpacity>
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  form: { padding: 20 },
  label: { fontSize: 13, fontWeight: '600', marginBottom: 6, marginTop: 14 },
  input: { height: 44, borderRadius: 10, borderWidth: 1, paddingHorizontal: 14, fontSize: 15 },
  bodyHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginTop: 14, marginBottom: 6 },
  aiBtn: { paddingHorizontal: 12, paddingVertical: 6, borderRadius: 16 },
  aiBtnText: { color: '#FFF', fontSize: 13, fontWeight: '600' },
  textArea: { height: 200, borderRadius: 10, borderWidth: 1, padding: 14, fontSize: 15, lineHeight: 22 },
  compliance: { fontSize: 11, marginTop: 8, fontStyle: 'italic' },
  sendBtn: { height: 50, borderRadius: 12, justifyContent: 'center', alignItems: 'center', marginTop: 20 },
  sendBtnText: { color: '#FFF', fontSize: 17, fontWeight: '700' },
});
