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

export interface CalcuttaItemResultsProps {
    item: CalcuttaAuctionItemProps;
    item_results: CalcuttaItemResultProps[];
    market_type: string;
}

export const CalcuttaItemResults: React.FC<CalcuttaItemResultsProps> = ({
    item,
    item_results,
    market_type,
}) => {
    const { theme } = useTheme();

    const results = [...item_results]
        .filter(r => r.calcutta_auction_item_id === item.calcutta_auction_item_id)
        .sort((a, b) => (a.round_number ?? 0) - (b.round_number ?? 0));

    const totalPayout = results.reduce((sum, r) => sum + Number(r.payout_earned), 0);

    const getResultIcon = (result: string): { name: keyof typeof Ionicons.glyphMap; color: string } => {
        switch (result) {
            case 'advanced':
                return { name: 'checkmark-circle', color: theme.colors.status.success };
            case 'eliminated':
                return { name: 'close-circle', color: theme.colors.status.error };
            case 'won':
                return { name: 'trophy', color: '#FFD700' };
            case 'placed':
                return { name: 'medal-outline', color: theme.colors.primary.default };
            default:
                return { name: 'ellipse-outline', color: theme.colors.text.tertiary };
        }
    };

    const renderResult = ({ item: result }: { item: CalcuttaItemResultProps }) => {
        const icon = getResultIcon(result.result);
        return (
            <View
                variant="transparent"
                style={[styles.resultRow, { borderColor: theme.colors.border.subtle }]}
            >
                <View variant="transparent" style={styles.roundCol}>
                    <Text variant="caption" color="secondary">
                        R{result.round_number ?? '-'}
                    </Text>
                </View>
                <Ionicons name={icon.name} size={16} color={icon.color} style={styles.resultIcon} />
                <View variant="transparent" style={styles.resultInfo}>
                    <Text variant="body">{getStatusLabel(result.result)}</Text>
                    {result.placement != null && (
                        <Text variant="caption" color="tertiary">
                            Placement: {result.placement}
                        </Text>
                    )}
                </View>
                <View variant="transparent" style={styles.payoutCol}>
                    {result.payout_earned > 0 ? (
                        <Text variant="caption" style={{ color: theme.colors.status.success }}>
                            +{formatCurrency(result.payout_earned, market_type)}
                        </Text>
                    ) : (
                        <Text variant="caption" color="tertiary">-</Text>
                    )}
                    {result.processed && (
                        <Ionicons name="checkmark" size={12} color={theme.colors.status.success} style={{ marginTop: 2 }} />
                    )}
                </View>
            </View>
        );
    };

    return (
        <View variant="transparent" style={styles.container}>
            {/* Item header */}
            <View variant="transparent" style={[styles.header, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                <View variant="transparent" style={styles.headerLeft}>
                    <View variant="transparent" style={[styles.itemIcon, { backgroundColor: theme.colors.surface.base }]}>
                        <Ionicons
                            name={item.item_type === 'team' ? 'people-outline' : 'person-outline'}
                            size={18}
                            color={theme.colors.text.tertiary}
                        />
                    </View>
                    <View variant="transparent" style={styles.headerInfo}>
                        <Text variant="body" bold numberOfLines={1}>{item.item_name}</Text>
                        <Text variant="caption" color="tertiary">
                            {item.seed != null ? `#${item.seed} Seed` : item.item_type}
                            {' \u00B7 '}
                            {getStatusLabel(item.status)}
                        </Text>
                    </View>
                </View>
                <View variant="transparent" style={styles.headerRight}>
                    <Text variant="caption" color="tertiary">Won for</Text>
                    <Text variant="body" bold>
                        {item.winning_bid > 0 ? formatCurrency(item.winning_bid, market_type) : '-'}
                    </Text>
                </View>
            </View>

            {/* Summary */}
            <View variant="transparent" style={[styles.summary, { borderColor: theme.colors.border.subtle }]}>
                <View variant="transparent" style={styles.summaryItem}>
                    <Text variant="caption" color="tertiary">Rounds</Text>
                    <Text variant="body" bold>{results.length}</Text>
                </View>
                <View variant="transparent" style={styles.summaryItem}>
                    <Text variant="caption" color="tertiary">Advanced</Text>
                    <Text variant="body" bold style={{ color: theme.colors.status.success }}>
                        {results.filter(r => r.result === 'advanced' || r.result === 'won').length}
                    </Text>
                </View>
                <View variant="transparent" style={styles.summaryItem}>
                    <Text variant="caption" color="tertiary">Total Payout</Text>
                    <Text variant="body" bold style={{ color: totalPayout > 0 ? theme.colors.status.success : theme.colors.text.primary }}>
                        {formatCurrency(totalPayout, market_type)}
                    </Text>
                </View>
            </View>

            {/* Results list */}
            <FlatList
                data={results}
                keyExtractor={r => r.calcutta_item_result_id}
                renderItem={renderResult}
                ListEmptyComponent={
                    <Text variant="caption" color="tertiary" style={styles.emptyText}>
                        No results yet
                    </Text>
                }
            />
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    header: {
        flexDirection: 'row',
        alignItems: 'center',
        padding: 12,
        borderBottomWidth: 1,
    },
    headerLeft: {
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
    },
    itemIcon: {
        width: 36,
        height: 36,
        borderRadius: 18,
        alignItems: 'center',
        justifyContent: 'center',
    },
    headerInfo: {
        flex: 1,
        marginLeft: 10,
    },
    headerRight: {
        alignItems: 'flex-end',
        marginLeft: 10,
    },
    summary: {
        flexDirection: 'row',
        paddingVertical: 10,
        paddingHorizontal: 12,
        borderBottomWidth: 1,
    },
    summaryItem: {
        flex: 1,
        alignItems: 'center',
    },
    resultRow: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 10,
        paddingHorizontal: 12,
        borderBottomWidth: 1,
    },
    roundCol: {
        width: 30,
    },
    resultIcon: {
        marginRight: 8,
    },
    resultInfo: {
        flex: 1,
    },
    payoutCol: {
        alignItems: 'flex-end',
        marginLeft: 10,
    },
    emptyText: {
        textAlign: 'center',
        padding: 20,
    },
});
