import React, { useEffect, useRef } from 'react';
import { StyleSheet, View, Text, Modal, TouchableOpacity, FlatList, Dimensions, Animated, Platform } from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { X, Bell, CheckCircle } from 'lucide-react-native';
import { useTheme } from '@/context/ThemeContext';
import useTradeStore from '@/store/useTradeStore';

interface MessageModalProps {
  visible: boolean;
  onClose: () => void;
}

const { width } = Dimensions.get('window');

export default function MessageModal({ visible, onClose }: MessageModalProps) {
  const { theme, colors } = useTheme();
  const { messages, markMessagesAsRead } = useTradeStore();
  
  // Animation values
  const slideAnim = useRef(new Animated.Value(Platform.OS === 'web' ? 0 : width)).current;
  const opacityAnim = useRef(new Animated.Value(0)).current;
  
  useEffect(() => {
    if (visible) {
      markMessagesAsRead();
      
      // Animate in from right side
      Animated.parallel([
        Animated.timing(slideAnim, {
          toValue: 0,
          duration: 300,
          useNativeDriver: Platform.OS !== 'web',
        }),
        Animated.timing(opacityAnim, {
          toValue: 1,
          duration: 300,
          useNativeDriver: Platform.OS !== 'web',
        }),
      ]).start();
    } else {
      // Reset animation values
      slideAnim.setValue(Platform.OS === 'web' ? 0 : width);
      opacityAnim.setValue(0);
    }
  }, [visible]);
  
  const handleClose = () => {
    // Animate out before closing
    Animated.parallel([
      Animated.timing(slideAnim, {
        toValue: Platform.OS === 'web' ? 0 : width,
        duration: 250,
        useNativeDriver: Platform.OS !== 'web',
      }),
      Animated.timing(opacityAnim, {
        toValue: 0,
        duration: 250,
        useNativeDriver: Platform.OS !== 'web',
      }),
    ]).start(() => {
      onClose();
    });
  };
  
  const formatDate = (dateString: string) => {
    try {
      const date = new Date(dateString);
      return date.toLocaleDateString(undefined, { 
        month: 'short', 
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    } catch (error) {
      console.error("Error formatting date:", error);
      return "Unknown date";
    }
  };
  
  const renderItem = ({ item }) => (
    <View style={[styles.messageItem, { backgroundColor: colors.backgroundSecondary }]}>
      <View style={styles.messageHeader}>
        <Text style={[styles.messageTitle, { color: colors.text }]}>{item.title}</Text>
        <Text style={[styles.messageDate, { color: colors.textSecondary }]}>
          {formatDate(item.timestamp)}
        </Text>
      </View>
      <Text style={[styles.messageBody, { color: colors.textSecondary }]}>{item.body}</Text>
    </View>
  );
  
  return (
    <Modal
      visible={visible}
      transparent={true}
      animationType="none"
      onRequestClose={handleClose}
    >
      <View style={styles.modalContainer}>
        <Animated.View 
          style={[
            styles.modalContent, 
            { 
              backgroundColor: colors.background,
              opacity: opacityAnim,
              transform: Platform.OS === 'web' 
                ? [] 
                : [{ translateX: slideAnim }]
            }
          ]}
        >
          {theme === 'dark' && (
            <LinearGradient
              colors={['rgba(30, 39, 46, 0.8)', 'rgba(0, 0, 0, 1)']}
              style={styles.backgroundGradient}
            />
          )}
          
          <View style={styles.modalHeader}>
            <View style={styles.headerLeft}>
              <Bell size={20} color={colors.primary} />
              <Text style={[styles.modalTitle, { color: colors.text }]}>Notifications</Text>
            </View>
            <TouchableOpacity onPress={handleClose} style={styles.closeButton}>
              <X size={20} color={colors.textSecondary} />
            </TouchableOpacity>
          </View>
          
          {messages.length > 0 ? (
            <FlatList
              data={messages}
              renderItem={renderItem}
              keyExtractor={(item) => item.id}
              contentContainerStyle={styles.messagesList}
              showsVerticalScrollIndicator={false}
            />
          ) : (
            <View style={styles.emptyContainer}>
              <CheckCircle size={40} color={colors.textSecondary} />
              <Text style={[styles.emptyText, { color: colors.textSecondary }]}>
                No notifications yet
              </Text>
            </View>
          )}
        </Animated.View>
      </View>
    </Modal>
  );
}

const styles = StyleSheet.create({
  modalContainer: {
    flex: 1,
    justifyContent: 'flex-end',
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
  },
  modalContent: {
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    height: '80%',
    width: '100%',
    overflow: 'hidden',
    position: 'relative',
  },
  backgroundGradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  modalHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 16,
    borderBottomWidth: 1,
    borderBottomColor: 'rgba(255, 255, 255, 0.1)',
  },
  headerLeft: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginLeft: 8,
  },
  closeButton: {
    padding: 4,
  },
  messagesList: {
    padding: 16,
  },
  messageItem: {
    borderRadius: 12,
    padding: 16,
    marginBottom: 12,
  },
  messageHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    marginBottom: 8,
  },
  messageTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    flex: 1,
    marginRight: 8,
  },
  messageDate: {
    fontSize: 12,
  },
  messageBody: {
    fontSize: 14,
    lineHeight: 20,
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  emptyText: {
    fontSize: 16,
    marginTop: 16,
  },
});