import React from 'react';
import { StyleSheet, FlatList, Image } from 'react-native';
import { View, Text, useTheme } from '@bettoredge/styles';
import { Ionicons } from '@expo/vector-icons';
import type { CalcuttaParticipantProps, PublicPlayerProps } from '@bettoredge/types';
import { formatCurrency, formatPlace } from '../helpers/formatting';

export interface CalcuttaLeaderboardProps {
    participants: CalcuttaParticipantProps[];
    players?: Record<string, PublicPlayerProps>;
    player_id?: string;
    market_type: string;
    listHeader?: React.ReactNode;
}

export const CalcuttaLeaderboard: React.FC<CalcuttaLeaderboardProps> = ({
    participants,
    players,
    player_id,
    market_type,
    listHeader,
}) => {
    const { theme } = useTheme();

    const sorted = [...participants].sort((a, b) => {
        if (a.place && b.place) return a.place - b.place;
        if (a.place) return -1;
        if (b.place) return 1;
        return b.total_winnings - a.total_winnings;
    });

    const renderHeader = () => (
        <View variant="transparent">
            <>{listHeader}</>
            <View
                variant="transparent"
                style={[styles.headerRow, { borderColor: theme.colors.border.subtle, backgroundColor: theme.colors.surface.elevated }]}
            >
                <Text variant="caption" color="tertiary" style={styles.placeCol}>#</Text>
                <Text variant="caption" color="tertiary" style={styles.playerCol}>Player</Text>
                <Text variant="caption" color="tertiary" style={styles.numCol}>Items</Text>
                <Text variant="caption" color="tertiary" style={styles.numCol}>Spent</Text>
                <Text variant="caption" color="tertiary" style={styles.numCol}>Won</Text>
            </View>
        </View>
    );

    const renderItem = ({ item, index }: { item: CalcuttaParticipantProps; index: number }) => {
        const place = item.place ?? index + 1;
        const isPositive = item.total_winnings > item.total_spent;
        const isMe = item.player_id === player_id;
        const player = players?.[item.player_id];
        const username = player?.username || player?.show_name || `Player ${item.player_id.slice(0, 6)}`;
        const profilePic = player?.profile_pic;

        return (
            <View
                variant="transparent"
                style={[styles.row, { borderColor: theme.colors.border.subtle }, isMe && { backgroundColor: theme.colors.primary.subtle + '40' }]}
            >
                <View variant="transparent" style={styles.placeCol}>
                    {place <= 3 ? (
                        <Ionicons
                            name="trophy"
                            size={14}
                            color={place === 1 ? '#FFD700' : place === 2 ? '#C0C0C0' : '#CD7F32'}
                        />
                    ) : (
                        <Text variant="caption" color="secondary">{formatPlace(place)}</Text>
                    )}
                </View>
                <View variant="transparent" style={styles.playerInfo}>
                    {profilePic ? (
                        <Image source={{ uri: profilePic }} style={styles.avatar} />
                    ) : (
                        <View variant="transparent" style={[styles.avatar, { backgroundColor: theme.colors.primary.subtle }]}>
                            <Text variant="caption" bold style={{ color: theme.colors.primary.default, fontSize: 10, lineHeight: 13 }}>
                                {username.charAt(0).toUpperCase()}
                            </Text>
                        </View>
                    )}
                    <View variant="transparent" style={{ flex: 1, marginLeft: 8 }}>
                        <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center' }}>
                            <Text variant="body" bold={isMe} numberOfLines={1} style={{ flex: 1 }}>{username}</Text>
                            {isMe && (
                                <View variant="transparent" style={[styles.youBadge, { backgroundColor: theme.colors.primary.subtle }]}>
                                    <Text variant="caption" bold style={{ color: theme.colors.primary.default, fontSize: 9, lineHeight: 12 }}>YOU</Text>
                                </View>
                            )}
                        </View>
                    </View>
                </View>
                <Text variant="caption" color="secondary" style={styles.numCol}>
                    {item.items_owned}
                </Text>
                <Text variant="caption" color="secondary" style={styles.numCol}>
                    {formatCurrency(item.total_spent, market_type)}
                </Text>
                <Text
                    variant="caption"
                    bold={isPositive}
                    style={[
                        styles.numCol,
                        { color: isPositive ? theme.colors.status.success : theme.colors.text.secondary },
                    ]}
                >
                    {formatCurrency(item.total_winnings, market_type)}
                </Text>
            </View>
        );
    };

    return (
        <FlatList
            data={sorted}
            keyExtractor={item => item.calcutta_participant_id}
            ListHeaderComponent={renderHeader}
            renderItem={renderItem}
            ListEmptyComponent={
                <Text variant="caption" color="tertiary" style={styles.emptyText}>
                    No participants yet
                </Text>
            }
        />
    );
};

const styles = StyleSheet.create({
    headerRow: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 8,
        paddingHorizontal: 12,
        borderBottomWidth: 1,
    },
    row: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 10,
        paddingHorizontal: 12,
        borderBottomWidth: 1,
    },
    placeCol: {
        width: 32,
        alignItems: 'center',
    },
    playerInfo: {
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
        marginLeft: 4,
    },
    playerCol: {
        flex: 1,
        marginLeft: 4,
    },
    avatar: {
        width: 28,
        height: 28,
        borderRadius: 14,
        alignItems: 'center',
        justifyContent: 'center',
        overflow: 'hidden',
    },
    youBadge: {
        paddingHorizontal: 5,
        paddingVertical: 1,
        borderRadius: 4,
        marginLeft: 4,
    },
    numCol: {
        width: 60,
        textAlign: 'right',
    },
    emptyText: {
        textAlign: 'center',
        padding: 20,
    },
});
