import React, { useRef, useEffect, memo } from 'react';
import { StyleSheet, View, Text, Animated, Easing } from 'react-native';
import { TradeHistory } from '@/types';
import { TrendingUp, TrendingDown, Minus, Clock } from 'lucide-react-native';
import { LinearGradient } from 'expo-linear-gradient';
import useTradeStore from '@/store/useTradeStore';
import { useTheme } from '@/context/ThemeContext';

interface TradeHistoryItemProps {
  trade: TradeHistory;
  index?: number;
}

const TradeHistoryItem = memo(({ trade, index = 0 }: TradeHistoryItemProps) => {
  const { isUserFromNigeria } = useTradeStore();
  const { colors, theme } = useTheme();
  
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const slideAnim = useRef(new Animated.Value(50)).current;
  
  useEffect(() => {
    // Staggered animation based on index
    const delay = index * 100;
    
    Animated.parallel([
      Animated.timing(fadeAnim, {
        toValue: 1,
        duration: 500,
        delay,
        useNativeDriver: true,
        easing: Easing.out(Easing.ease),
      }),
      Animated.timing(slideAnim, {
        toValue: 0,
        duration: 500,
        delay,
        useNativeDriver: true,
        easing: Easing.out(Easing.ease),
      }),
    ]).start();
    
    // Cleanup animation
    return () => {
      fadeAnim.stopAnimation();
      slideAnim.stopAnimation();
    };
  }, [index]);
  
  const formatDate = (dateString: string) => {
    try {
      const date = new Date(dateString);
      return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    } catch (error) {
      console.error("Date formatting error:", error);
      return "Recent";
    }
  };
  
  const isProfit = trade.profitLoss > 0;
  const isLoss = trade.profitLoss < 0;
  const isDraw = trade.profitLoss === 0;
  
  const currencySymbol = isUserFromNigeria ? 'NGN' : 'USDT';
  
  return (
    <Animated.View 
      style={[
        styles.container,
        { 
          opacity: fadeAnim,
          transform: [{ translateY: slideAnim }],
          borderColor: theme === 'dark' ? 'rgba(74, 101, 114, 0.2)' : 'rgba(200, 200, 200, 0.5)',
          backgroundColor: theme === 'dark' ? 'transparent' : colors.card
        }
      ]}
    >
      {theme === 'dark' && (
        <LinearGradient
          colors={
            isProfit ? ['rgba(46, 204, 113, 0.2)', 'rgba(46, 204, 113, 0.05)'] :
            isLoss ? ['rgba(231, 76, 60, 0.2)', 'rgba(231, 76, 60, 0.05)'] :
            ['rgba(41, 171, 226, 0.2)', 'rgba(41, 171, 226, 0.05)']
          }
          style={styles.backgroundGradient}
        />
      )}
      
      <View style={[styles.header, { borderBottomColor: colors.border }]}>
        <View style={styles.marketInfo}>
          <Text style={[styles.marketName, { color: colors.text }]}>{trade.market}</Text>
          <Text style={[styles.tradeType, { color: colors.textSecondary }]}>{trade.type}</Text>
        </View>
        
        <View style={[
          styles.statusContainer,
          isProfit ? styles.profitStatus :
          isLoss ? styles.lossStatus :
          styles.drawStatus
        ]}>
          {isProfit ? (
            <TrendingUp size={14} color={colors.success} />
          ) : isLoss ? (
            <TrendingDown size={14} color={colors.error} />
          ) : (
            <Minus size={14} color={colors.primary} />
          )}
          <Text style={[
            styles.statusText,
            isProfit ? styles.profitText :
            isLoss ? styles.lossText :
            styles.drawText
          ]}>
            {isProfit ? 'Win' : isLoss ? 'Loss' : 'Draw'}
          </Text>
        </View>
      </View>
      
      <View style={styles.details}>
        <View style={styles.detailRow}>
          <Text style={[styles.detailLabel, { color: colors.textSecondary }]}>Investment:</Text>
          <Text style={[styles.detailValue, { color: colors.text }]}>{trade.investment.toFixed(2)} BATZ</Text>
        </View>
        
        <View style={styles.detailRow}>
          <Text style={[styles.detailLabel, { color: colors.textSecondary }]}>Price:</Text>
          <Text style={[styles.detailValue, { color: colors.text }]}>{trade.price.toFixed(2)}</Text>
        </View>
        
        <View style={styles.detailRow}>
          <Text style={[styles.detailLabel, { color: colors.textSecondary }]}>Profit/Loss:</Text>
          <Text style={[
            styles.detailValue,
            isProfit ? styles.profitText :
            isLoss ? styles.lossText :
            styles.drawText
          ]}>
            {isProfit ? '+' : isLoss ? '-' : ''}
            {Math.abs(trade.profitLoss).toFixed(2)} {currencySymbol}
          </Text>
        </View>
      </View>
      
      <View style={styles.footer}>
        <View style={styles.timeContainer}>
          <Clock size={12} color={colors.textSecondary} />
          <Text style={[styles.timeText, { color: colors.textSecondary }]}>{formatDate(trade.timestamp)}</Text>
        </View>
      </View>
    </Animated.View>
  );
});

export default TradeHistoryItem;

const styles = StyleSheet.create({
  container: {
    borderRadius: 12,
    marginBottom: 12,
    overflow: 'hidden',
    position: 'relative',
    borderWidth: 1,
  },
  backgroundGradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 12,
    borderBottomWidth: 1,
  },
  marketInfo: {
    flexDirection: 'column',
  },
  marketName: {
    fontSize: 16,
    fontWeight: 'bold',
  },
  tradeType: {
    fontSize: 12,
  },
  statusContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 4,
  },
  profitStatus: {
    backgroundColor: 'rgba(46, 204, 113, 0.1)',
  },
  lossStatus: {
    backgroundColor: 'rgba(231, 76, 60, 0.1)',
  },
  drawStatus: {
    backgroundColor: 'rgba(41, 171, 226, 0.1)',
  },
  statusText: {
    fontSize: 12,
    fontWeight: '500',
    marginLeft: 4,
  },
  profitText: {
    color: '#2ECC71',
  },
  lossText: {
    color: '#E74C3C',
  },
  drawText: {
    color: '#29ABE2',
  },
  details: {
    padding: 12,
  },
  detailRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 6,
  },
  detailLabel: {
    fontSize: 14,
  },
  detailValue: {
    fontSize: 14,
    fontWeight: '500',
  },
  footer: {
    padding: 12,
    paddingTop: 0,
  },
  timeContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  timeText: {
    fontSize: 12,
    marginLeft: 4,
  },
});