import React, { useEffect, useRef } from 'react';
import { StyleSheet, TouchableOpacity, Animated, Dimensions, FlatList } from 'react-native';
import { View, Text, useTheme } from '@bettoredge/styles';
import { Ionicons } from '@expo/vector-icons';
import type { CalcuttaAuctionItemProps } from '@bettoredge/types';
import { formatCurrency } from '../../helpers/formatting';

interface AuctionResultsModalProps {
    visible: boolean;
    onDismiss: () => void;
    wonItems: CalcuttaAuctionItemProps[];
    market_type: string;
}

const SCREEN_HEIGHT = Dimensions.get('window').height;

export const AuctionResultsModal: React.FC<AuctionResultsModalProps> = ({
    visible,
    onDismiss,
    wonItems,
    market_type,
}) => {
    const { theme } = useTheme();
    const scaleAnim = useRef(new Animated.Value(0.8)).current;
    const opacityAnim = useRef(new Animated.Value(0)).current;

    useEffect(() => {
        if (visible) {
            Animated.parallel([
                Animated.spring(scaleAnim, {
                    toValue: 1,
                    friction: 6,
                    tension: 40,
                    useNativeDriver: true,
                }),
                Animated.timing(opacityAnim, {
                    toValue: 1,
                    duration: 300,
                    useNativeDriver: true,
                }),
            ]).start();
        } else {
            scaleAnim.setValue(0.8);
            opacityAnim.setValue(0);
        }
    }, [visible]);

    if (!visible) return null;

    const totalSpent = wonItems.reduce((s, i) => s + Number(i.winning_bid), 0);
    const hasWins = wonItems.length > 0;

    return (
        <Animated.View style={[StyleSheet.absoluteFill, styles.overlay, { opacity: opacityAnim }]}>
            <Animated.View
                style={[
                    styles.modal,
                    {
                        backgroundColor: theme.colors.surface.base,
                        transform: [{ scale: scaleAnim }],
                    },
                ]}
            >
                {/* Header */}
                <View variant="transparent" style={styles.header}>
                    {hasWins ? (
                        <>
                            <Ionicons name="trophy" size={48} color="#F59E0B" />
                            <Text variant="h2" bold style={{ marginTop: 12 }}>
                                Congratulations!
                            </Text>
                            <Text variant="body" color="secondary" style={{ marginTop: 4, textAlign: 'center' }}>
                                You won {wonItems.length} item{wonItems.length !== 1 ? 's' : ''} for {formatCurrency(totalSpent, market_type)}
                            </Text>
                        </>
                    ) : (
                        <>
                            <Ionicons name="ribbon-outline" size={48} color={theme.colors.text.tertiary} />
                            <Text variant="h2" bold style={{ marginTop: 12 }}>
                                Auction Complete
                            </Text>
                            <Text variant="body" color="secondary" style={{ marginTop: 4, textAlign: 'center' }}>
                                You didn't win any items this time. Better luck next auction!
                            </Text>
                        </>
                    )}
                </View>

                {/* Won items list */}
                {hasWins && (
                    <View variant="transparent" style={styles.itemsList}>
                        {wonItems.slice(0, 6).map(item => (
                            <View
                                key={item.calcutta_auction_item_id}
                                variant="transparent"
                                style={[styles.wonItem, { backgroundColor: theme.colors.status.successSubtle }]}
                            >
                                <Ionicons name="checkmark-circle" size={16} color={theme.colors.status.success} />
                                <Text variant="body" bold style={{ flex: 1, marginLeft: 8 }} numberOfLines={1}>
                                    {item.item_name}
                                </Text>
                                <Text variant="body" bold style={{ color: theme.colors.status.success }}>
                                    {formatCurrency(item.winning_bid, market_type)}
                                </Text>
                            </View>
                        ))}
                        {wonItems.length > 6 && (
                            <Text variant="caption" color="tertiary" style={{ textAlign: 'center', marginTop: 4 }}>
                                +{wonItems.length - 6} more item{wonItems.length - 6 !== 1 ? 's' : ''}
                            </Text>
                        )}
                    </View>
                )}

                {/* CTA */}
                <TouchableOpacity
                    style={[styles.ctaButton, { backgroundColor: theme.colors.primary.default }]}
                    onPress={onDismiss}
                    activeOpacity={0.7}
                >
                    <Text variant="body" bold style={{ color: '#FFFFFF' }}>
                        {hasWins ? 'View My Items' : 'View Results'}
                    </Text>
                </TouchableOpacity>
            </Animated.View>
        </Animated.View>
    );
};

const styles = StyleSheet.create({
    overlay: {
        backgroundColor: 'rgba(0,0,0,0.6)',
        alignItems: 'center',
        justifyContent: 'center',
        padding: 24,
    },
    modal: {
        width: '100%',
        maxWidth: 360,
        borderRadius: 16,
        padding: 24,
        alignItems: 'center',
    },
    header: {
        alignItems: 'center',
        marginBottom: 20,
    },
    itemsList: {
        width: '100%',
        marginBottom: 20,
        gap: 8,
    },
    wonItem: {
        flexDirection: 'row',
        alignItems: 'center',
        padding: 10,
        borderRadius: 8,
    },
    ctaButton: {
        width: '100%',
        paddingVertical: 14,
        borderRadius: 10,
        alignItems: 'center',
    },
});
