/**
 * AI Chat — conversational assistant powered by Ollama.
 * Ask about clients, market data, draft emails, get coaching.
 */

import React, { useState, useRef, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TextInput,
  TouchableOpacity,
  KeyboardAvoidingView,
  Platform,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useTheme } from '../../themes/ThemeProvider';
import AIBubble from '../../components/AIBubble';
import { chatAI } from '../../services/api';

interface Message {
  id: string;
  text: string;
  isAI: boolean;
  timestamp: string;
}

const QUICK_PROMPTS = [
  'Summarize my pipeline',
  'Draft a follow-up email',
  'What tasks are overdue?',
  'Market update for today',
  'Coaching: improve conversion',
];

export default function ChatScreen() {
  const { theme } = useTheme();
  const [messages, setMessages] = useState<Message[]>([
    {
      id: '0',
      text: 'Hello! I\'m your Fogbreak AI assistant. Ask me about your clients, deals, market data, or anything else. I can also draft emails, summarize your pipeline, and provide coaching insights.',
      isAI: true,
      timestamp: new Date().toISOString(),
    },
  ]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const flatListRef = useRef<FlatList>(null);

  const sendMessage = useCallback(async (text: string) => {
    if (!text.trim() || loading) return;

    const userMsg: Message = {
      id: `user_${Date.now()}`,
      text: text.trim(),
      isAI: false,
      timestamp: new Date().toISOString(),
    };

    setMessages((prev) => [...prev, userMsg]);
    setInput('');
    setLoading(true);

    setTimeout(() => {
      flatListRef.current?.scrollToEnd({ animated: true });
    }, 100);

    const res = await chatAI(text.trim(), {
      conversation_history: messages.slice(-10).map((m) => ({
        role: m.isAI ? 'assistant' : 'user',
        content: m.text,
      })),
    });

    const aiMsg: Message = {
      id: `ai_${Date.now()}`,
      text: res.success && res.data
        ? (res.data as { response: string }).response
        : res.error ?? 'Sorry, I couldn\'t process that request. Please try again.',
      isAI: true,
      timestamp: new Date().toISOString(),
    };

    setMessages((prev) => [...prev, aiMsg]);
    setLoading(false);

    setTimeout(() => {
      flatListRef.current?.scrollToEnd({ animated: true });
    }, 100);
  }, [loading, messages]);

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.colors.background }]} edges={['bottom']}>
      <KeyboardAvoidingView
        style={styles.container}
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
        keyboardVerticalOffset={90}
      >
        <FlatList
          ref={flatListRef}
          data={messages}
          keyExtractor={(item) => item.id}
          renderItem={({ item }) => (
            <AIBubble message={item.text} isAI={item.isAI} timestamp={item.timestamp} />
          )}
          contentContainerStyle={styles.messageList}
          ListHeaderComponent={
            messages.length <= 1 ? (
              <View style={styles.quickPrompts}>
                <Text style={[styles.quickTitle, { color: theme.colors.textSecondary }]}>Try asking:</Text>
                {QUICK_PROMPTS.map((prompt) => (
                  <TouchableOpacity
                    key={prompt}
                    style={[styles.quickChip, { backgroundColor: theme.colors.card, borderColor: theme.colors.border }]}
                    onPress={() => sendMessage(prompt)}
                  >
                    <Text style={[styles.quickText, { color: theme.colors.text }]}>{prompt}</Text>
                  </TouchableOpacity>
                ))}
              </View>
            ) : null
          }
        />

        {loading && (
          <View style={styles.typingIndicator}>
            <Text style={[styles.typingText, { color: theme.colors.textSecondary }]}>
              AI is thinking...
            </Text>
          </View>
        )}

        <View style={[styles.inputBar, { backgroundColor: theme.colors.card, borderTopColor: theme.colors.border }]}>
          <TextInput
            style={[styles.input, { color: theme.colors.text, backgroundColor: theme.colors.inputBg }]}
            value={input}
            onChangeText={setInput}
            placeholder="Ask anything..."
            placeholderTextColor={theme.colors.textSecondary}
            multiline
            maxLength={2000}
            returnKeyType="send"
            onSubmitEditing={() => sendMessage(input)}
            blurOnSubmit
          />
          <TouchableOpacity
            style={[styles.sendBtn, {
              backgroundColor: input.trim() ? theme.colors.primary : theme.colors.border,
            }]}
            onPress={() => sendMessage(input)}
            disabled={!input.trim() || loading}
          >
            <Text style={styles.sendIcon}>↑</Text>
          </TouchableOpacity>
        </View>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1 },
  container: { flex: 1 },
  messageList: { paddingVertical: 12 },
  quickPrompts: { padding: 16, gap: 8 },
  quickTitle: { fontSize: 14, fontWeight: '600', marginBottom: 4 },
  quickChip: {
    paddingHorizontal: 14,
    paddingVertical: 10,
    borderRadius: 10,
    borderWidth: 1,
  },
  quickText: { fontSize: 14 },
  typingIndicator: { paddingHorizontal: 20, paddingVertical: 4 },
  typingText: { fontSize: 13, fontStyle: 'italic' },
  inputBar: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    padding: 10,
    borderTopWidth: StyleSheet.hairlineWidth,
    gap: 8,
  },
  input: {
    flex: 1,
    minHeight: 40,
    maxHeight: 100,
    borderRadius: 20,
    paddingHorizontal: 16,
    paddingVertical: 10,
    fontSize: 15,
  },
  sendBtn: {
    width: 36,
    height: 36,
    borderRadius: 18,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 2,
  },
  sendIcon: { color: '#FFF', fontSize: 18, fontWeight: '700' },
});
