/**
 * Chat Screen - Text Chat with Julia AI
 *
 * Clean text chat interface.
 * Voice calls are handled by separate voice-call.tsx screen.
 */

import React, { useState, useCallback, useRef, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TextInput,
  TouchableOpacity,
  KeyboardAvoidingView,
  Platform,
  Modal,
  ActivityIndicator,
  Keyboard,
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { api } from '@/services/api';
import { useBeneficiary } from '@/contexts/BeneficiaryContext';
import { useVoiceTranscript } from '@/contexts/VoiceTranscriptContext';
import { AppColors, BorderRadius, FontSizes, Spacing } from '@/constants/theme';
import type { Message, Beneficiary } from '@/types';

const API_URL = 'https://eluxnetworks.net/function/well-api/api';

// WellNuo API credentials (same as julia-agent)
const WELLNUO_USER = 'anandk';
const WELLNUO_PASSWORD = 'anandk_8';

// Keywords for question normalization (same as julia-agent/julia-ai/src/agent.py)
const STATUS_KEYWORDS = [
  /\bhow\s+is\b/i,
  /\bhow'?s\b/i,
  /\bhow\s+are\b/i,
  /\btell\s+me\s+about\b/i,
  /\bwhat'?s\s+up\s+with\b/i,
  /\bupdate\s+on\b/i,
  /\bstatus\b/i,
  /\bdoing\b/i,
  /\bfeeling\b/i,
  /\bcheck\s+on\b/i,
  /\bis\s+\w+\s+okay\b/i,
  /\bis\s+\w+\s+alright\b/i,
  /\bis\s+\w+\s+fine\b/i,
  /\bokay\?\b/i,
  /\balright\?\b/i,
];

const SUBJECT_KEYWORDS = [
  /\bdad\b/i,
  /\bfather\b/i,
  /\bferdinand\b/i,
  /\bhim\b/i,
  /\bhe\b/i,
  /\bmy\s+dad\b/i,
  /\bmy\s+father\b/i,
  /\bthe\s+patient\b/i,
  /\bloved\s+one\b/i,
  /\bparent\b/i,
  /\bgrandpa\b/i,
  /\bgrandfather\b/i,
];

/**
 * Transform user questions into format WellNuo API understands.
 * WellNuo API only responds with real sensor data for very specific phrases.
 * This function maps common user questions to those phrases.
 * (Same logic as julia-agent/julia-ai/src/agent.py normalize_question)
 */
function normalizeQuestion(userMessage: string): string {
  const msgLower = userMessage.toLowerCase().trim();

  const isStatusQuery = STATUS_KEYWORDS.some(pattern => pattern.test(msgLower));
  const isAboutRecipient = SUBJECT_KEYWORDS.some(pattern => pattern.test(msgLower));

  // If asking about the care recipient's general status
  if (isStatusQuery && isAboutRecipient) {
    console.log(`[Chat] Normalized '${userMessage}' -> 'how is dad doing'`);
    return 'how is dad doing';
  }

  // Generic status questions without clear subject - assume they mean the care recipient
  if (isStatusQuery && !isAboutRecipient) {
    console.log(`[Chat] Normalized '${userMessage}' -> 'how is dad doing' (assumed recipient)`);
    return 'how is dad doing';
  }

  // If no transformation needed, return original
  console.log(`[Chat] No normalization applied to: '${userMessage}'`);
  return userMessage;
}

export default function ChatScreen() {
  const router = useRouter();
  const { currentBeneficiary, setCurrentBeneficiary } = useBeneficiary();
  const { getTranscriptAsMessages, hasNewTranscript, markTranscriptAsShown } = useVoiceTranscript();

  // Chat state
  const [messages, setMessages] = useState<Message[]>([
    {
      id: '1',
      role: 'assistant',
      content: 'Hello! I\'m Julia, your AI wellness assistant. You can type a message or tap the phone button to start a voice call.',
      timestamp: new Date(),
    },
  ]);

  // Add voice call transcript to messages when returning from call
  useEffect(() => {
    if (hasNewTranscript) {
      const transcriptMessages = getTranscriptAsMessages();
      if (transcriptMessages.length > 0) {
        // Add a separator message
        const separatorMessage: Message = {
          id: `voice-separator-${Date.now()}`,
          role: 'assistant',
          content: '--- Voice Call Transcript ---',
          timestamp: new Date(),
          isSystem: true,
        };

        setMessages(prev => [...prev, separatorMessage, ...transcriptMessages]);
        markTranscriptAsShown();

        // Scroll to bottom
        setTimeout(() => {
          flatListRef.current?.scrollToEnd({ animated: true });
        }, 100);
      }
    }
  }, [hasNewTranscript, getTranscriptAsMessages, markTranscriptAsShown]);
  const [input, setInput] = useState('');
  const [isSending, setIsSending] = useState(false);
  const flatListRef = useRef<FlatList>(null);

  // Beneficiary picker
  const [showBeneficiaryPicker, setShowBeneficiaryPicker] = useState(false);
  const [beneficiaries, setBeneficiaries] = useState<Beneficiary[]>([]);
  const [loadingBeneficiaries, setLoadingBeneficiaries] = useState(false);

  // Load beneficiaries
  const loadBeneficiaries = useCallback(async () => {
    setLoadingBeneficiaries(true);
    try {
      const response = await api.getAllBeneficiaries();
      if (response.ok && response.data) {
        setBeneficiaries(response.data);
        return response.data;
      }
      return [];
    } catch (error) {
      console.error('Failed to load beneficiaries:', error);
      return [];
    } finally {
      setLoadingBeneficiaries(false);
    }
  }, []);

  // Auto-select first beneficiary
  useEffect(() => {
    const autoSelect = async () => {
      if (!currentBeneficiary) {
        const loaded = await loadBeneficiaries();
        if (loaded.length > 0) {
          setCurrentBeneficiary(loaded[0]);
        }
      }
    };
    autoSelect();
  }, []);

  const openBeneficiaryPicker = useCallback(() => {
    setShowBeneficiaryPicker(true);
    loadBeneficiaries();
  }, [loadBeneficiaries]);

  const selectBeneficiary = useCallback((beneficiary: Beneficiary) => {
    setCurrentBeneficiary(beneficiary);
    setShowBeneficiaryPicker(false);
  }, [setCurrentBeneficiary]);

  // Start voice call - navigate to voice-call screen
  const startVoiceCall = useCallback(() => {
    router.push('/voice-call');
  }, [router]);

  // Cached API token for WellNuo
  const apiTokenRef = useRef<string | null>(null);

  // Get WellNuo API token (same credentials as julia-agent)
  const getWellNuoToken = useCallback(async (): Promise<string> => {
    if (apiTokenRef.current) {
      return apiTokenRef.current;
    }

    const nonce = Math.floor(Math.random() * 1000000).toString();
    const response = await fetch(API_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({
        function: 'credentials',
        clientId: 'MA_001',
        user_name: WELLNUO_USER,
        ps: WELLNUO_PASSWORD,
        nonce: nonce,
      }).toString(),
    });

    const data = await response.json();
    if (data.status === '200 OK' && data.access_token) {
      apiTokenRef.current = data.access_token;
      console.log('[Chat] WellNuo token obtained');
      return data.access_token;
    }
    throw new Error('Failed to authenticate with WellNuo API');
  }, []);

  // Text chat - send message via API (same as julia-agent)
  const sendTextMessage = useCallback(async () => {
    const trimmedInput = input.trim();
    if (!trimmedInput || isSending) return;

    const userMessage: Message = {
      id: Date.now().toString(),
      role: 'user',
      content: trimmedInput,
      timestamp: new Date(),
    };

    setMessages(prev => [...prev, userMessage]);
    setInput('');
    setIsSending(true);
    Keyboard.dismiss();

    try {
      // Get WellNuo API token (uses anandk credentials like julia-agent)
      const token = await getWellNuoToken();

      // Normalize question to format WellNuo API understands
      // (same logic as julia-agent/julia-ai/src/agent.py)
      const normalizedQuestion = normalizeQuestion(trimmedInput);

      // Call API with EXACT same params as voice agent
      // Using ask_wellnuo_ai instead of voice_ask (same params, same response format)
      const response = await fetch(API_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
          function: 'ask_wellnuo_ai',
          clientId: 'MA_001',
          user_name: WELLNUO_USER,
          token: token,
          question: normalizedQuestion,
          deployment_id: '21',
        }).toString(),
      });

      const data = await response.json();

      if (data.ok && data.response?.body) {
        const assistantMessage: Message = {
          id: (Date.now() + 1).toString(),
          role: 'assistant',
          content: data.response.body,
          timestamp: new Date(),
        };
        setMessages(prev => [...prev, assistantMessage]);
      } else {
        // Token might be expired, clear and retry once
        if (data.status === '401 Unauthorized') {
          apiTokenRef.current = null;
          throw new Error('Session expired, please try again');
        }
        throw new Error('Could not get response');
      }
    } catch (error) {
      const errorMessage: Message = {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: `Sorry, I encountered an error: ${error instanceof Error ? error.message : 'Unknown error'}`,
        timestamp: new Date(),
      };
      setMessages(prev => [...prev, errorMessage]);
    } finally {
      setIsSending(false);
    }
  }, [input, isSending, getWellNuoToken]);

  // Render message bubble
  const renderMessage = ({ item }: { item: Message }) => {
    const isUser = item.role === 'user';
    const isVoice = item.isVoice;
    const isSystem = item.isSystem;

    // System messages (like "Voice Call Transcript" separator)
    if (isSystem) {
      return (
        <View style={styles.systemMessageContainer}>
          <View style={styles.systemMessageLine} />
          <View style={styles.systemMessageBadge}>
            <Ionicons name="call" size={12} color={AppColors.textMuted} />
            <Text style={styles.systemMessageText}>{item.content.replace(/---/g, '').trim()}</Text>
          </View>
          <View style={styles.systemMessageLine} />
        </View>
      );
    }

    return (
      <View style={[styles.messageContainer, isUser ? styles.userMessageContainer : styles.assistantMessageContainer]}>
        {!isUser && (
          <View style={styles.avatarContainer}>
            <Text style={styles.avatarText}>J</Text>
          </View>
        )}
        <View style={[styles.messageBubble, isUser ? styles.userBubble : styles.assistantBubble, isVoice && styles.voiceBubble]}>
          {isVoice && (
            <View style={styles.voiceIndicator}>
              <Ionicons name="mic" size={12} color={isUser ? 'rgba(255,255,255,0.7)' : AppColors.textMuted} />
            </View>
          )}
          <Text style={[styles.messageText, isUser ? styles.userMessageText : styles.assistantMessageText]}>
            {item.content}
          </Text>
          <Text style={[styles.timestamp, isUser && styles.userTimestamp]}>
            {item.timestamp.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
          </Text>
        </View>
      </View>
    );
  };

  return (
    <SafeAreaView style={styles.container} edges={['top']}>
      {/* Header */}
      <View style={styles.header}>
        <TouchableOpacity style={styles.backButton} onPress={() => router.push('/(tabs)')}>
          <Ionicons name="arrow-back" size={24} color={AppColors.textPrimary} />
        </TouchableOpacity>
        <View style={styles.headerInfo}>
          <View style={styles.headerAvatar}>
            <Text style={styles.headerAvatarText}>J</Text>
          </View>
          <View>
            <Text style={styles.headerTitle}>Julia AI</Text>
            <Text style={styles.headerSubtitle}>
              {currentBeneficiary ? `About ${currentBeneficiary.name}` : 'Online'}
            </Text>
          </View>
        </View>
        <View style={styles.headerButtons}>
          {/* Voice Call Button */}
          <TouchableOpacity style={styles.callButton} onPress={startVoiceCall}>
            <Ionicons name="call" size={22} color={AppColors.white} />
          </TouchableOpacity>
        </View>
      </View>

      {/* Beneficiary Picker Modal */}
      <Modal
        visible={showBeneficiaryPicker}
        transparent
        animationType="slide"
        onRequestClose={() => setShowBeneficiaryPicker(false)}
      >
        <View style={styles.modalOverlay}>
          <View style={styles.modalContent}>
            <View style={styles.modalHeader}>
              <Text style={styles.modalTitle}>Select Beneficiary</Text>
              <TouchableOpacity onPress={() => setShowBeneficiaryPicker(false)}>
                <Ionicons name="close" size={24} color={AppColors.textPrimary} />
              </TouchableOpacity>
            </View>

            {loadingBeneficiaries ? (
              <View style={styles.modalLoading}>
                <ActivityIndicator size="large" color={AppColors.primary} />
              </View>
            ) : beneficiaries.length === 0 ? (
              <View style={styles.modalEmpty}>
                <Text style={styles.emptyText}>No beneficiaries found</Text>
              </View>
            ) : (
              <FlatList
                data={beneficiaries}
                keyExtractor={(item) => item.id.toString()}
                renderItem={({ item }) => (
                  <TouchableOpacity
                    style={[
                      styles.beneficiaryItem,
                      currentBeneficiary?.id === item.id && styles.beneficiaryItemSelected,
                    ]}
                    onPress={() => selectBeneficiary(item)}
                  >
                    <View style={styles.beneficiaryAvatar}>
                      <Text style={styles.beneficiaryAvatarText}>
                        {item.name.split(' ').map(n => n[0]).join('').slice(0, 2)}
                      </Text>
                    </View>
                    <View style={styles.beneficiaryInfo}>
                      <Text style={styles.beneficiaryName}>{item.name}</Text>
                    </View>
                    {currentBeneficiary?.id === item.id && (
                      <Ionicons name="checkmark-circle" size={24} color={AppColors.success} />
                    )}
                  </TouchableOpacity>
                )}
                style={styles.beneficiaryList}
              />
            )}
          </View>
        </View>
      </Modal>

      {/* Messages */}
      <KeyboardAvoidingView
        style={styles.chatContainer}
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
        keyboardVerticalOffset={Platform.OS === 'ios' ? 90 : 0}
      >
        <FlatList
          ref={flatListRef}
          data={messages}
          keyExtractor={(item) => item.id}
          renderItem={renderMessage}
          contentContainerStyle={styles.messagesList}
          showsVerticalScrollIndicator={false}
          onContentSizeChange={() => flatListRef.current?.scrollToEnd({ animated: true })}
        />

        {/* Input */}
        <View style={styles.inputContainer}>
          {/* Voice Call Button in input area */}
          <TouchableOpacity style={styles.voiceCallButton} onPress={startVoiceCall}>
            <Ionicons name="call-outline" size={20} color={AppColors.primary} />
          </TouchableOpacity>

          <TextInput
            style={styles.input}
            placeholder="Type a message..."
            placeholderTextColor={AppColors.textMuted}
            value={input}
            onChangeText={setInput}
            multiline
            maxLength={1000}
            onSubmitEditing={sendTextMessage}
          />
          <TouchableOpacity
            style={[styles.sendButton, (!input.trim() || isSending) && styles.sendButtonDisabled]}
            onPress={sendTextMessage}
            disabled={!input.trim() || isSending}
          >
            <Ionicons
              name={isSending ? 'hourglass' : 'send'}
              size={20}
              color={input.trim() && !isSending ? AppColors.white : AppColors.textMuted}
            />
          </TouchableOpacity>
        </View>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: AppColors.surface,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: Spacing.md,
    paddingVertical: Spacing.sm,
    backgroundColor: AppColors.background,
    borderBottomWidth: 1,
    borderBottomColor: AppColors.border,
  },
  backButton: {
    padding: Spacing.xs,
    marginRight: Spacing.sm,
  },
  headerInfo: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
  headerAvatar: {
    width: 40,
    height: 40,
    borderRadius: BorderRadius.full,
    backgroundColor: AppColors.success,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: Spacing.sm,
  },
  headerAvatarText: {
    fontSize: FontSizes.lg,
    fontWeight: '600',
    color: AppColors.white,
  },
  headerTitle: {
    fontSize: FontSizes.lg,
    fontWeight: '600',
    color: AppColors.textPrimary,
  },
  headerSubtitle: {
    fontSize: FontSizes.sm,
    color: AppColors.success,
  },
  headerButtons: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: Spacing.sm,
  },
  callButton: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: AppColors.success,
    justifyContent: 'center',
    alignItems: 'center',
  },
  headerButton: {
    padding: Spacing.xs,
  },
  chatContainer: {
    flex: 1,
  },
  messagesList: {
    padding: Spacing.md,
    paddingBottom: Spacing.lg,
  },
  messageContainer: {
    flexDirection: 'row',
    marginBottom: Spacing.md,
    alignItems: 'flex-end',
  },
  userMessageContainer: {
    justifyContent: 'flex-end',
  },
  assistantMessageContainer: {
    justifyContent: 'flex-start',
  },
  avatarContainer: {
    width: 32,
    height: 32,
    borderRadius: BorderRadius.full,
    backgroundColor: AppColors.success,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: Spacing.xs,
  },
  avatarText: {
    fontSize: FontSizes.sm,
    fontWeight: '600',
    color: AppColors.white,
  },
  messageBubble: {
    maxWidth: '75%',
    padding: Spacing.sm + 4,
    borderRadius: BorderRadius.lg,
  },
  userBubble: {
    backgroundColor: AppColors.primary,
    borderBottomRightRadius: BorderRadius.sm,
  },
  assistantBubble: {
    backgroundColor: AppColors.background,
    borderBottomLeftRadius: BorderRadius.sm,
  },
  messageText: {
    fontSize: FontSizes.base,
    lineHeight: 22,
  },
  userMessageText: {
    color: AppColors.white,
  },
  assistantMessageText: {
    color: AppColors.textPrimary,
  },
  timestamp: {
    fontSize: FontSizes.xs,
    color: AppColors.textMuted,
    marginTop: Spacing.xs,
    alignSelf: 'flex-end',
  },
  userTimestamp: {
    color: 'rgba(255,255,255,0.7)',
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    padding: Spacing.md,
    backgroundColor: AppColors.background,
    borderTopWidth: 1,
    borderTopColor: AppColors.border,
  },
  voiceCallButton: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: AppColors.surface,
    borderWidth: 1,
    borderColor: AppColors.primary,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: Spacing.sm,
  },
  input: {
    flex: 1,
    backgroundColor: AppColors.surface,
    borderRadius: BorderRadius.xl,
    paddingHorizontal: Spacing.md,
    paddingVertical: Spacing.sm,
    fontSize: FontSizes.base,
    color: AppColors.textPrimary,
    maxHeight: 100,
    marginRight: Spacing.sm,
  },
  sendButton: {
    width: 44,
    height: 44,
    borderRadius: BorderRadius.full,
    backgroundColor: AppColors.primary,
    justifyContent: 'center',
    alignItems: 'center',
  },
  sendButtonDisabled: {
    backgroundColor: AppColors.surface,
  },
  // Modal styles
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'flex-end',
  },
  modalContent: {
    backgroundColor: AppColors.background,
    borderTopLeftRadius: BorderRadius.xl,
    borderTopRightRadius: BorderRadius.xl,
    maxHeight: '70%',
    paddingBottom: Spacing.xl,
  },
  modalHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: Spacing.md,
    borderBottomWidth: 1,
    borderBottomColor: AppColors.border,
  },
  modalTitle: {
    fontSize: FontSizes.lg,
    fontWeight: '600',
    color: AppColors.textPrimary,
  },
  modalLoading: {
    padding: Spacing.xl,
    alignItems: 'center',
  },
  modalEmpty: {
    padding: Spacing.xl,
    alignItems: 'center',
  },
  emptyText: {
    fontSize: FontSizes.base,
    color: AppColors.textSecondary,
  },
  beneficiaryList: {
    paddingHorizontal: Spacing.md,
  },
  beneficiaryItem: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: Spacing.md,
    backgroundColor: AppColors.surface,
    borderRadius: BorderRadius.md,
    marginTop: Spacing.sm,
  },
  beneficiaryItemSelected: {
    backgroundColor: AppColors.primaryLight || '#E3F2FD',
    borderWidth: 1,
    borderColor: AppColors.primary,
  },
  beneficiaryAvatar: {
    width: 44,
    height: 44,
    borderRadius: BorderRadius.full,
    backgroundColor: AppColors.primary,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: Spacing.md,
  },
  beneficiaryAvatarText: {
    fontSize: FontSizes.base,
    fontWeight: '600',
    color: AppColors.white,
  },
  beneficiaryInfo: {
    flex: 1,
  },
  beneficiaryName: {
    fontSize: FontSizes.base,
    fontWeight: '500',
    color: AppColors.textPrimary,
  },
  // Voice message styles
  voiceBubble: {
    borderWidth: 1,
    borderColor: 'rgba(59, 130, 246, 0.3)',
  },
  voiceIndicator: {
    position: 'absolute',
    top: 6,
    right: 6,
  },
  // System message styles
  systemMessageContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginVertical: Spacing.md,
    paddingHorizontal: Spacing.md,
  },
  systemMessageLine: {
    flex: 1,
    height: 1,
    backgroundColor: AppColors.border,
  },
  systemMessageBadge: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: Spacing.sm,
    paddingVertical: 4,
    backgroundColor: AppColors.surface,
    borderRadius: BorderRadius.sm,
    marginHorizontal: Spacing.sm,
  },
  systemMessageText: {
    fontSize: FontSizes.xs,
    color: AppColors.textMuted,
    marginLeft: 4,
  },
});
