import React, { useEffect, useRef } from 'react';
import { StyleSheet, Animated, ScrollView, Image, TouchableOpacity } 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 PlayerSummary {
    player_id: string;
    username?: string;
    profile_pic?: string;
    items_won: number;
    total_spent: number;
    is_me?: boolean;
}

export interface AuctionCompleteOverlayProps {
    visible: boolean;
    competitionName?: string;
    totalPot: number;
    marketType: string;
    myItemsWon: CalcuttaAuctionItemProps[];
    myTotalSpent: number;
    leaderboard: PlayerSummary[];
    onDismiss: () => void;
}

export const AuctionCompleteOverlay: React.FC<AuctionCompleteOverlayProps> = ({
    visible,
    competitionName,
    totalPot,
    marketType,
    myItemsWon,
    myTotalSpent,
    leaderboard,
    onDismiss,
}) => {
    const { theme } = useTheme();
    const opacityAnim = useRef(new Animated.Value(0)).current;
    const slideAnim = useRef(new Animated.Value(40)).current;

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

    if (!visible) return null;

    const medals = ['🥇', '🥈', '🥉'];

    return (
        <Animated.View style={[styles.overlay, { opacity: opacityAnim }]}>
            <View variant="transparent" style={styles.backdrop} />
            <Animated.View style={[styles.content, { transform: [{ translateY: slideAnim }] }]}>
                <ScrollView
                    showsVerticalScrollIndicator={false}
                    contentContainerStyle={styles.scrollContent}
                >
                    {/* Header */}
                    <Ionicons name="trophy" size={48} color="#F59E0B" />
                    <Text style={styles.title}>Auction Complete!</Text>
                    <Text style={styles.compName}>{competitionName}</Text>

                    {/* Total pot */}
                    <View variant="transparent" style={styles.potCard}>
                        <Text style={styles.potLabel}>Total Pot</Text>
                        <Text style={styles.potAmount}>{formatCurrency(totalPot, marketType)}</Text>
                    </View>

                    {/* My results */}
                    {myItemsWon.length > 0 ? (
                        <View variant="transparent" style={styles.section}>
                            <Text style={styles.sectionTitle}>Your Items ({myItemsWon.length})</Text>
                            {myItemsWon.map(item => (
                                <View key={item.calcutta_auction_item_id} variant="transparent" style={styles.itemRow}>
                                    <Ionicons name="checkmark-circle" size={16} color="#10B981" />
                                    <Text style={styles.itemName} numberOfLines={1}>{item.item_name}</Text>
                                    <Text style={styles.itemBid}>{formatCurrency(item.winning_bid, marketType)}</Text>
                                </View>
                            ))}
                            <View variant="transparent" style={styles.totalRow}>
                                <Text style={styles.totalLabel}>Total Spent</Text>
                                <Text style={styles.totalAmount}>{formatCurrency(myTotalSpent, marketType)}</Text>
                            </View>
                        </View>
                    ) : (
                        <View variant="transparent" style={styles.section}>
                            <Text style={styles.noItems}>You didn't win any items this auction</Text>
                        </View>
                    )}

                    {/* Leaderboard */}
                    {leaderboard.length > 0 && (
                        <View variant="transparent" style={styles.section}>
                            <Text style={styles.sectionTitle}>Leaderboard</Text>
                            {leaderboard.map((player, i) => (
                                <View key={player.player_id} variant="transparent" style={styles.leaderRow}>
                                    <Text style={styles.rank}>{i < 3 ? medals[i] : `${i + 1}`}</Text>
                                    {player.profile_pic ? (
                                        <Image source={{ uri: player.profile_pic }} style={styles.avatar} />
                                    ) : (
                                        <View variant="transparent" style={[styles.avatar, { backgroundColor: player.is_me ? '#10B98130' : 'rgba(255,255,255,0.15)', alignItems: 'center', justifyContent: 'center' }]}>
                                            <Text style={{ color: player.is_me ? '#10B981' : '#FFFFFF', fontSize: 11, lineHeight: 15, fontWeight: '700' }}>
                                                {(player.username || '?').charAt(0).toUpperCase()}
                                            </Text>
                                        </View>
                                    )}
                                    <View variant="transparent" style={{ flex: 1, marginLeft: 8 }}>
                                        <Text style={[styles.leaderName, player.is_me && { color: '#10B981' }]}>
                                            {player.is_me ? 'You' : player.username || 'Player'}
                                        </Text>
                                        <Text style={styles.leaderSub}>
                                            {player.items_won} item{player.items_won !== 1 ? 's' : ''}
                                        </Text>
                                    </View>
                                    <Text style={styles.leaderSpent}>{formatCurrency(player.total_spent, marketType)}</Text>
                                </View>
                            ))}
                        </View>
                    )}

                    {/* Dismiss */}
                    <TouchableOpacity style={styles.dismissBtn} onPress={onDismiss} activeOpacity={0.7}>
                        <Text style={styles.dismissText}>Continue</Text>
                    </TouchableOpacity>
                </ScrollView>
            </Animated.View>
        </Animated.View>
    );
};

const styles = StyleSheet.create({
    overlay: {
        ...StyleSheet.absoluteFillObject,
        zIndex: 997,
        alignItems: 'center',
        justifyContent: 'center',
    },
    backdrop: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: 'rgba(0,0,0,0.85)',
    },
    content: {
        width: '90%',
        maxWidth: 400,
        maxHeight: '85%',
        backgroundColor: '#1a1a2e',
        borderRadius: 24,
        overflow: 'hidden',
    },
    scrollContent: {
        padding: 28,
        alignItems: 'center',
    },
    title: {
        color: '#FFFFFF',
        fontSize: 26,
        lineHeight: 34,
        fontWeight: '900',
        marginTop: 12,
    },
    compName: {
        color: 'rgba(255,255,255,0.5)',
        fontSize: 14,
        lineHeight: 19,
        marginTop: 4,
        marginBottom: 20,
    },
    potCard: {
        backgroundColor: 'rgba(245,158,11,0.15)',
        borderRadius: 14,
        paddingVertical: 16,
        paddingHorizontal: 24,
        alignItems: 'center',
        width: '100%',
        marginBottom: 20,
    },
    potLabel: {
        color: '#F59E0B',
        fontSize: 12,
        lineHeight: 16,
        textTransform: 'uppercase',
        letterSpacing: 1,
    },
    potAmount: {
        color: '#F59E0B',
        fontSize: 32,
        lineHeight: 42,
        fontWeight: '900',
        marginTop: 4,
    },
    section: {
        width: '100%',
        marginBottom: 16,
    },
    sectionTitle: {
        color: 'rgba(255,255,255,0.5)',
        fontSize: 11,
        lineHeight: 15,
        textTransform: 'uppercase',
        letterSpacing: 1,
        marginBottom: 10,
    },
    itemRow: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 8,
        borderBottomWidth: 1,
        borderBottomColor: 'rgba(255,255,255,0.08)',
    },
    itemName: {
        color: '#FFFFFF',
        fontSize: 14,
        lineHeight: 19,
        flex: 1,
        marginLeft: 8,
    },
    itemBid: {
        color: 'rgba(255,255,255,0.7)',
        fontSize: 14,
        lineHeight: 19,
        fontWeight: '600',
    },
    totalRow: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        paddingTop: 10,
    },
    totalLabel: {
        color: 'rgba(255,255,255,0.5)',
        fontSize: 13,
        lineHeight: 17,
    },
    totalAmount: {
        color: '#FFFFFF',
        fontSize: 16,
        lineHeight: 21,
        fontWeight: '800',
    },
    noItems: {
        color: 'rgba(255,255,255,0.4)',
        fontSize: 14,
        lineHeight: 19,
        textAlign: 'center',
        paddingVertical: 12,
    },
    leaderRow: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 8,
        borderBottomWidth: 1,
        borderBottomColor: 'rgba(255,255,255,0.08)',
    },
    rank: {
        color: '#FFFFFF',
        fontSize: 16,
        lineHeight: 21,
        width: 28,
        textAlign: 'center',
    },
    avatar: {
        width: 28,
        height: 28,
        borderRadius: 14,
    },
    leaderName: {
        color: '#FFFFFF',
        fontSize: 14,
        lineHeight: 19,
        fontWeight: '600',
    },
    leaderSub: {
        color: 'rgba(255,255,255,0.4)',
        fontSize: 11,
        lineHeight: 15,
    },
    leaderSpent: {
        color: 'rgba(255,255,255,0.7)',
        fontSize: 14,
        lineHeight: 19,
        fontWeight: '600',
    },
    dismissBtn: {
        backgroundColor: '#10B981',
        height: 48,
        borderRadius: 12,
        alignItems: 'center',
        justifyContent: 'center',
        width: '100%',
        marginTop: 8,
    },
    dismissText: {
        color: '#FFFFFF',
        fontSize: 16,
        lineHeight: 21,
        fontWeight: '700',
    },
});
