import React, { useRef, useEffect } from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity, Platform, ViewStyle, TextStyle } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import * as Clipboard from 'expo-clipboard';
import { MessagesProps, Message } from '../../types';

// Default sample messages for demo
const defaultMessages: Message[] = [
  {
    id: 1,
    role: 'user',
    content: 'provide me shorter message',
    timestamp: new Date().toISOString(),
  },
  {
    id: 2,
    role: 'assistant',
    content: `Here are some recent scientific discoveries:

🚀 Space: JWST found tiny asteroids, and Voyager 1 re-established contact.

🧬 Medicine: New malaria vaccines, Alzheimer's drug (Kisunla), and the Human Cell Atlas.

🌎 Environment: 27 new species discovered in Peru, a new rock skink found in Australia.

💻 Tech: Google DeepMind's AI (Gemini), advances in quantum computing.

For more, check FT and NYPost. 🚀`,
    timestamp: new Date().toISOString(),
  }
];

const Messages: React.FC<MessagesProps> = ({
  messages = defaultMessages,
  onCopy,
  onRegenerate,
  containerStyle,
  bubbleStyle,
  messageTextStyle,
  fontFamily,
  theme = 'dark',
  customActions
}) => {
  const flatListRef = useRef<FlatList>(null);
  const colors = getThemeColors(theme);
  
  useEffect(() => {
    // Scroll to bottom when messages change
    if (flatListRef.current) {
      setTimeout(() => {
        flatListRef.current?.scrollToEnd({ animated: true });
      }, 100);
    }
  }, [messages]);
  
  const formatMessageContent = (content: string) => {
    return content.split('\n').map((line, i) => {
      if (line.trim() === '') {
        return <View key={i} style={{ height: 8 }} />;
      }
      return (
        <Text 
          key={i} 
          style={[
            styles.messageText, 
            { color: colors.textColor, fontFamily },
            messageTextStyle
          ]}
        >
          {line}
        </Text>
      );
    });
  };
  
  const copyToClipboard = async (text: string, messageId: number | string) => {
    await Clipboard.setStringAsync(text);
    if (onCopy) {
      onCopy(text);
    }
  };

  const handleRegenerate = (messageId: number | string) => {
    if (onRegenerate) {
      onRegenerate(messageId);
    }
  };
  
  const renderMessage = ({ item }: { item: Message }) => {
    const isUser = item.role === 'user';
    
    return (
      <View style={[
        styles.messageContainer,
        isUser ? styles.userMessageContainer : styles.assistantMessageContainer
      ]}>
        <View style={styles.messageHeader}>
          <Text style={[styles.senderName, { color: colors.secondaryTextColor }]}>
            {isUser ? 'You' : 'Assistant'}
          </Text>
          <Text style={[styles.timestamp, { color: colors.secondaryTextColor }]}>
            {new Date(item.timestamp).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}
          </Text>
        </View>
        
        <View style={[
          styles.messageBubble, 
          isUser ? 
            { backgroundColor: colors.userBubbleBg } : 
            { backgroundColor: colors.assistantBubbleBg },
          bubbleStyle
        ]}>
          {formatMessageContent(item.content)}
          
          {!isUser && (
            <View style={[styles.messageActions, { borderTopColor: colors.borderColor }]}>
              <TouchableOpacity 
                onPress={() => copyToClipboard(item.content, item.id)} 
                style={styles.actionButton}
              >
                <Ionicons name="copy-outline" size={16} color={colors.iconColor} />
              </TouchableOpacity>
              
              <TouchableOpacity style={styles.actionButton}>
                <Ionicons name="square-outline" size={16} color={colors.iconColor} />
              </TouchableOpacity>
              
              <TouchableOpacity 
                style={styles.actionButton} 
                onPress={() => handleRegenerate(item.id)}
              >
                <Ionicons name="refresh-outline" size={16} color={colors.iconColor} />
              </TouchableOpacity>
              
              <TouchableOpacity style={styles.actionButton}>
                <Ionicons name="ellipsis-horizontal" size={16} color={colors.iconColor} />
              </TouchableOpacity>

              {/* Render custom actions if provided */}
              {customActions && customActions.map((action, index) => (
                <TouchableOpacity 
                  key={`custom-action-${index}`} 
                  style={styles.actionButton}
                  onPress={() => action.onPress(item.id)}
                >
                  {action.icon}
                </TouchableOpacity>
              ))}
            </View>
          )}
        </View>
      </View>
    );
  };

  return (
    <FlatList
      ref={flatListRef}
      data={messages}
      renderItem={renderMessage}
      keyExtractor={(item) => item.id.toString()}
      contentContainerStyle={[styles.messagesContainer, containerStyle]}
      showsVerticalScrollIndicator={Platform.OS === 'web'}
    />
  );
};

// Theme helper function
function getThemeColors(theme: 'light' | 'dark') {
  if (theme === 'light') {
    return {
      backgroundColor: '#ffffff',
      userBubbleBg: '#e5e7eb',
      assistantBubbleBg: '#f3f4f6',
      textColor: '#111827',
      secondaryTextColor: '#6b7280',
      iconColor: '#6b7280',
      borderColor: '#d1d5db'
    };
  }
  
  return {
    backgroundColor: '#111827',
    userBubbleBg: '#4B5563',
    assistantBubbleBg: '#1F2937',
    textColor: '#F9FAFB',
    secondaryTextColor: '#9CA3AF',
    iconColor: '#9CA3AF',
    borderColor: '#374151'
  };
}

const styles = StyleSheet.create({
  messagesContainer: {
    padding: 16,
    paddingBottom: 80, // Space for input
  },
  messageContainer: {
    marginBottom: 16,
    maxWidth: '80%',
  },
  userMessageContainer: {
    alignSelf: 'flex-end',
  },
  assistantMessageContainer: {
    alignSelf: 'flex-start',
  },
  messageHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 4,
  },
  senderName: {
    fontSize: 14,
    fontWeight: '600',
    marginRight: 8,
  },
  timestamp: {
    fontSize: 12,
  },
  messageBubble: {
    padding: 12,
    borderRadius: 20,
  },
  messageText: {
    fontSize: 15,
    marginBottom: 8,
  },
  messageActions: {
    flexDirection: 'row',
    marginTop: 8,
    paddingTop: 8,
    borderTopWidth: 1,
  },
  actionButton: {
    marginRight: 16,
  },
});

export default Messages;