// src/screens/ChatScreen.tsx
import React, { useState, useCallback, useRef, useEffect } from 'react';
import { View, StyleSheet, FlatList, KeyboardAvoidingView, Platform, TextInput as RNTextInput, NativeSyntheticEvent, TextInputKeyPressEventData } from 'react-native';
import { Text, useTheme, TextInput, Button, IconButton, PaperProvider } from 'react-native-paper';
import { SafeAreaView } from 'react-native-safe-area-context';
import apiClient from '../api/client'; // Import the apiClient

// Define the structure for a message
interface Message {
  id: string;
  text: string;
  sender: 'user' | 'ai';
  timestamp: Date;
}

// Define the expected structure for the API response from /nlp/process-command
interface NlpResponse {
  responses: string[];
}

// Define the expected structure for the API response from /nlp/history
interface ChatHistoryResponse {
  id: number;
  sender: 'user' | 'ai';
  text: string;
  timestamp: string; // Backend sends ISO string
}

const ChatScreen = () => {
  const theme = useTheme();
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputText, setInputText] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isHistoryLoading, setIsHistoryLoading] = useState(true); // Add state for history loading
  const flatListRef = useRef<FlatList>(null);

  // --- Load messages from backend API on mount ---
  useEffect(() => {
    const loadHistory = async () => {
      setIsHistoryLoading(true);
      try {
        console.log("[ChatScreen] Fetching chat history from /nlp/history");
        const response = await apiClient.get<ChatHistoryResponse[]>('/nlp/history');
        console.log("[ChatScreen] Received history:", response.data);

        if (response.data && Array.isArray(response.data)) {
          // Map backend response to frontend Message format
          const historyMessages = response.data.map((msg) => ({
            id: msg.id.toString(), // Convert backend ID to string for keyExtractor
            text: msg.text,
            sender: msg.sender,
            timestamp: new Date(msg.timestamp), // Convert ISO string to Date
          }));
          setMessages(historyMessages);
        } else {
          console.warn("[ChatScreen] Received invalid history data:", response.data);
          setMessages([]); // Set to empty array if data is invalid
        }
      } catch (error: any) {
        console.error("Failed to load chat history from backend:", error.response?.data || error.message || error);
        // Optionally, show an error message to the user
        // For now, just start with an empty chat
        setMessages([]);
      } finally {
        setIsHistoryLoading(false);
      }
    };
    loadHistory();
  }, []); // Empty dependency array ensures this runs only once on mount

  // Function to handle sending a message
  const handleSend = useCallback(async () => {
    const trimmedText = inputText.trim();
    if (!trimmedText || isLoading) return; // Prevent sending while loading

    const userMessage: Message = {
      id: Date.now().toString() + '-user', // Temporary frontend ID
      text: trimmedText,
      sender: 'user',
      timestamp: new Date(),
    };

    // Add user message optimistically
    setMessages(prevMessages => [...prevMessages, userMessage]);

    setInputText('');
    setIsLoading(true);

    // Scroll to bottom after sending user message
    setTimeout(() => flatListRef.current?.scrollToEnd({ animated: true }), 100);

    // --- Call Backend API ---
    try {
      console.log(`[ChatScreen] Sending to /nlp/process-command: ${trimmedText}`);
      const response = await apiClient.post<NlpResponse>('/nlp/process-command', { user_input: trimmedText });
      console.log("[ChatScreen] Received response:", response.data);

      const aiResponses: Message[] = [];
      if (response.data && Array.isArray(response.data.responses) && response.data.responses.length > 0) {
         response.data.responses.forEach((responseText, index) => {
            aiResponses.push({
              id: `${Date.now()}-ai-${index}`, // Temporary frontend ID
              text: responseText || "...",
              sender: 'ai',
              timestamp: new Date(),
            });
         });
      } else {
        console.warn("[ChatScreen] Received invalid or empty responses array:", response.data);
        aiResponses.push({
          id: Date.now().toString() + '-ai-fallback',
          text: "Sorry, I didn't get a valid response.",
          sender: 'ai',
          timestamp: new Date(),
        });
      }

      // Add all AI responses to the state
      setMessages(prevMessages => [...prevMessages, ...aiResponses]);

    } catch (error: any) {
      console.error("Failed to get AI response:", error.response?.data || error.message || error);
      const errorResponse: Message = {
        id: Date.now().toString() + '-error',
        text: 'Sorry, I encountered an error trying to reach MAIA.',
        sender: 'ai',
        timestamp: new Date(),
      };
       setMessages(prevMessages => [...prevMessages, errorResponse]);
    } finally {
      setIsLoading(false);
      // Scroll to bottom after receiving AI message(s)
      setTimeout(() => flatListRef.current?.scrollToEnd({ animated: true }), 100);
    }
    // --- End API Call ---

  }, [inputText, isLoading, messages]); // Add isLoading and messages to dependency array

  const handleKeyPress = (e: NativeSyntheticEvent<TextInputKeyPressEventData>) => {
    if (e.nativeEvent.key === 'Enter' && !(e.nativeEvent as any).shiftKey) {
      e.preventDefault(); // Prevent new line
      handleSend();
    }
  };

  // Render individual message item
  const renderMessage = ({ item }: { item: Message }) => {
    const isUser = item.sender === 'user';
    return (
      <View style={[styles.messageBubble, isUser ? styles.userBubble : styles.aiBubble]}>
        <Text style={{ color: isUser ? theme.colors.onPrimary : theme.colors.onSurface }}>
          {item.text}
        </Text>
        {/* Optional: Add timestamp */}
        {/* <Text style={[styles.timestamp, { color: isUser ? theme.colors.onPrimary : theme.colors.onSurfaceVariant }]}>
          {item.timestamp.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
        </Text> */}
      </View>
    );
  };

  const styles = StyleSheet.create({
    container: { // For SafeAreaView
      flex: 1,
      backgroundColor: theme.colors.background,
    },
    keyboardAvoidingContainer: { // Style for KAV
        flex: 1,
    },
    listContainer: { // Container for the list, should take up available space
      flex: 1,
    },
    messageList: { // Padding for the list content itself
      paddingHorizontal: 10,
      paddingVertical: 10,
    },
    inputContainer: { // Input container should stick to the bottom
      flexDirection: 'row',
      alignItems: 'center', // Align items vertically in the center
      paddingHorizontal: 8, // Add horizontal padding
      paddingVertical: 8,   // Add some vertical padding
      borderTopWidth: StyleSheet.hairlineWidth,
      borderTopColor: theme.colors.outlineVariant,
      backgroundColor: theme.colors.background, // Or theme.colors.surface
    },
    textInput: {
      flex: 1, // Take available horizontal space
      marginRight: 8,
      backgroundColor: theme.colors.surface,
      paddingTop: 10, // Keep the vertical alignment fix for placeholder
      paddingHorizontal: 10,
      // Add some vertical padding inside the input itself
      paddingVertical: Platform.OS === 'ios' ? 10 : 5, // Adjust padding for different platforms if needed
      maxHeight: 100, // Optional: prevent input from getting too tall with multiline
    },
    sendButton: {
       marginVertical: 4, // Adjust vertical alignment if needed
       // Ensure button doesn't shrink
       height: 40, // Match TextInput height approx.
       justifyContent: 'center',
    },
    messageBubble: {
      maxWidth: '80%',
      padding: 10,
      borderRadius: 15,
      marginBottom: 10,
    },
    userBubble: {
      alignSelf: 'flex-end',
      backgroundColor: theme.colors.primary,
      borderBottomRightRadius: 5,
    },
    aiBubble: {
      alignSelf: 'flex-start',
      backgroundColor: theme.colors.surfaceVariant,
      borderBottomLeftRadius: 5,
    },
    timestamp: {
        fontSize: 10,
        marginTop: 4,
        alignSelf: 'flex-end',
        opacity: 0.7,
    }
  });

  // Optionally, show a loading indicator while history loads
  if (isHistoryLoading) {
    return (
      <SafeAreaView style={styles.container} edges={['bottom', 'left', 'right']}>
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
          <Text>Loading chat history...</Text>
        </View>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.container} edges={['bottom', 'left', 'right']}>
      <KeyboardAvoidingView
        style={styles.keyboardAvoidingContainer} // Use style with flex: 1
        // Use 'padding' for both iOS and Android
        behavior={Platform.OS === "ios" ? "padding" : "padding"}
        // Remove keyboardVerticalOffset for Android when using padding.
        // Keep iOS offset if needed (e.g., for header).
        // Assuming headerHeight might be needed for iOS, otherwise set to 0.
        keyboardVerticalOffset={Platform.OS === "ios" ? 60 : 0} // Example iOS offset, adjust if necessary
      >
          {/* List container takes available space */}
          <View style={styles.listContainer}>
            <FlatList
              ref={flatListRef}
              data={messages}
              renderItem={renderMessage}
              keyExtractor={(item) => item.id}
              contentContainerStyle={styles.messageList} // Padding inside the scrollable content
              onContentSizeChange={() => flatListRef.current?.scrollToEnd({ animated: false })}
              onLayout={() => flatListRef.current?.scrollToEnd({ animated: false })}
            />
          </View>

          {/* Input container is last, outside the list's flex */}
          <View style={styles.inputContainer}>
            <TextInput
              style={styles.textInput}
              value={inputText}
              onChangeText={setInputText}
              placeholder="Type your message..."
              mode="outlined" // Keep outlined or flat as preferred
              multiline
              onKeyPress={handleKeyPress}
              blurOnSubmit={false} // Keep false for multiline + send button
              disabled={isLoading}
              dense // Try making the input slightly smaller vertically
            />
            <IconButton
              icon="send"
              size={24}
              onPress={handleSend}
              disabled={!inputText.trim() || isLoading}
              mode="contained"
              iconColor={theme.colors.onPrimary}
              containerColor={theme.colors.primary}
              style={styles.sendButton} // Apply style for alignment
            />
          </View>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
};

export default ChatScreen;