import React, { useState } from 'react';
import { StyleSheet, TouchableOpacity, Image } from 'react-native';
import { View, Text, useTheme } from '@bettoredge/styles';
import { Ionicons } from '@expo/vector-icons';
import type { CalcuttaAuctionItemProps, CalcuttaBidProps } from '@bettoredge/types';
import type { CalcuttaLifecycleState } from '../../helpers/lifecycleState';
import { formatCurrency } from '../../helpers/formatting';
import { CalcuttaBidInput } from '../CalcuttaBidInput';

interface SealedBidItemCardProps {
    item: CalcuttaAuctionItemProps;
    my_bid?: CalcuttaBidProps;
    min_bid: number;
    bid_increment: number;
    escrow_balance: number;
    market_type: string;
    player_id?: string;
    lifecycleState: CalcuttaLifecycleState;
    itemImage?: { url: string };
    onPlaceBid: (amount: number) => void;
    bidLoading: boolean;
    disabled?: boolean;
}

const QUICK_AMOUNTS = [5, 10, 25, 50];

export const SealedBidItemCard: React.FC<SealedBidItemCardProps> = ({
    item,
    my_bid,
    min_bid,
    bid_increment,
    escrow_balance,
    market_type,
    player_id,
    lifecycleState,
    itemImage,
    onPlaceBid,
    bidLoading,
    disabled,
}) => {
    const { theme } = useTheme();
    const [expanded, setExpanded] = useState(false);

    const hasBid = my_bid && my_bid.bid_status === 'active';
    const isSold = item.status === 'sold';
    const iOwnThis = isSold && item.winning_player_id === player_id;
    const canBidNow = lifecycleState === 'auctioning' && (item.status === 'active' || item.status === 'pending') && !disabled;

    // Resolve image: prefer fetched team/athlete image, fall back to stored item_image
    const resolvedImageUrl = itemImage?.url || item.item_image?.url;

    // ============================================
    // PENDING / SCHEDULED — Browse mode (info only)
    // ============================================
    if (lifecycleState === 'pending' || lifecycleState === 'scheduled') {
        return (
            <View
                variant="transparent"
                style={[
                    styles.card,
                    {
                        backgroundColor: theme.colors.surface.elevated,
                        borderColor: theme.colors.border.subtle,
                    },
                ]}
            >
                <View style={styles.row}>
                    <View variant="transparent" style={[styles.iconWrap, { backgroundColor: theme.colors.surface.base, overflow: 'hidden' }]}>
                        {resolvedImageUrl ? (
                            <Image source={{ uri: resolvedImageUrl }} style={styles.itemImage} resizeMode="contain" />
                        ) : (
                            <Ionicons
                                name={item.item_type === 'team' ? 'people-outline' : 'person-outline'}
                                size={16}
                                color={theme.colors.text.tertiary}
                            />
                        )}
                    </View>
                    <View variant="transparent" style={styles.info}>
                        <View variant="transparent" style={styles.nameRow}>
                            <Text variant="body" bold numberOfLines={1} style={{ flex: 1 }}>
                                {item.item_name}
                            </Text>
                            {item.seed != null && (
                                <Text variant="caption" color="tertiary" style={{ marginLeft: 6 }}>
                                    #{item.seed}
                                </Text>
                            )}
                        </View>
                        {item.item_type && (
                            <Text variant="caption" color="tertiary" style={{ marginTop: 2, fontSize: 11, lineHeight: 15 }}>
                                {item.item_type === 'team' ? 'Team' : 'Player'}
                            </Text>
                        )}
                    </View>
                </View>
            </View>
        );
    }

    // ============================================
    // TOURNAMENT / COMPLETED — Results view
    // ============================================
    if (lifecycleState === 'tournament' || lifecycleState === 'completed') {
        const didBid = my_bid != null;
        return (
            <View
                variant="transparent"
                style={[
                    styles.card,
                    {
                        backgroundColor: theme.colors.surface.elevated,
                        borderColor: iOwnThis
                            ? theme.colors.status.success + '80'
                            : theme.colors.border.subtle,
                    },
                    !isSold && { opacity: 0.5 },
                ]}
            >
                <View style={styles.row}>
                    <View variant="transparent" style={[styles.iconWrap, {
                        backgroundColor: iOwnThis
                            ? theme.colors.status.successSubtle
                            : theme.colors.surface.base,
                        overflow: 'hidden',
                    }]}>
                        {resolvedImageUrl ? (
                            <Image source={{ uri: resolvedImageUrl }} style={styles.itemImage} resizeMode="contain" />
                        ) : iOwnThis ? (
                            <Ionicons name="trophy" size={18} color="#F59E0B" />
                        ) : isSold ? (
                            <Ionicons name="close-circle" size={18} color={theme.colors.text.tertiary} />
                        ) : (
                            <Ionicons
                                name={item.item_type === 'team' ? 'people-outline' : 'person-outline'}
                                size={16}
                                color={theme.colors.text.tertiary}
                            />
                        )}
                    </View>
                    <View variant="transparent" style={styles.info}>
                        <View variant="transparent" style={styles.nameRow}>
                            <Text variant="body" bold numberOfLines={1} style={{ flex: 1 }}>
                                {item.item_name}
                            </Text>
                            {item.seed != null && (
                                <Text variant="caption" color="tertiary" style={{ marginLeft: 6 }}>
                                    #{item.seed}
                                </Text>
                            )}
                        </View>
                        <View variant="transparent" style={styles.metaRow}>
                            {iOwnThis && (
                                <View variant="transparent" style={[styles.wonBadge, { backgroundColor: theme.colors.status.successSubtle }]}>
                                    <Text variant="caption" bold style={{ color: theme.colors.status.success, fontSize: 10, lineHeight: 13 }}>
                                        YOU WON
                                    </Text>
                                </View>
                            )}
                            {isSold && !iOwnThis && didBid && (
                                <View variant="transparent" style={[styles.wonBadge, { backgroundColor: theme.colors.status.error + '15' }]}>
                                    <Text variant="caption" bold style={{ color: theme.colors.status.error, fontSize: 10, lineHeight: 13 }}>
                                        OUTBID
                                    </Text>
                                </View>
                            )}
                            {!isSold && (
                                <Text variant="caption" color="tertiary" style={{ fontSize: 10, lineHeight: 13 }}>Unsold</Text>
                            )}
                        </View>
                    </View>
                    <View variant="transparent" style={styles.bidCol}>
                        {isSold ? (
                            <>
                                <Text variant="caption" color="tertiary" style={{ fontSize: 10, lineHeight: 13 }}>
                                    {iOwnThis ? 'Paid' : 'Sold for'}
                                </Text>
                                <Text variant="body" bold style={{ color: iOwnThis ? theme.colors.status.success : theme.colors.text.primary }}>
                                    {formatCurrency(item.winning_bid, market_type)}
                                </Text>
                            </>
                        ) : (
                            <Text variant="caption" color="tertiary">No bids</Text>
                        )}
                    </View>
                </View>
                {didBid && isSold && !iOwnThis && (
                    <View variant="transparent" style={[styles.lostBidRow, { borderColor: theme.colors.border.subtle }]}>
                        <Text variant="caption" color="tertiary">Your bid: {formatCurrency(my_bid!.bid_amount, market_type)}</Text>
                    </View>
                )}
            </View>
        );
    }

    // ============================================
    // AUCTIONING — Active bid UI
    // ============================================
    return (
        <View
            variant="transparent"
            style={[
                styles.card,
                {
                    backgroundColor: theme.colors.surface.elevated,
                    borderColor: hasBid ? theme.colors.status.success + '60' : theme.colors.border.subtle,
                },
            ]}
        >
            <TouchableOpacity
                style={styles.row}
                activeOpacity={0.7}
                onPress={() => canBidNow && setExpanded(!expanded)}
                disabled={!canBidNow}
            >
                <View variant="transparent" style={[styles.iconWrap, { backgroundColor: theme.colors.surface.base, overflow: 'hidden' }]}>
                    {resolvedImageUrl ? (
                        <Image source={{ uri: resolvedImageUrl }} style={styles.itemImage} resizeMode="contain" />
                    ) : hasBid ? (
                        <Ionicons name="checkmark-circle" size={18} color={theme.colors.status.success} />
                    ) : (
                        <Ionicons
                            name={item.item_type === 'team' ? 'people-outline' : 'person-outline'}
                            size={16}
                            color={theme.colors.text.tertiary}
                        />
                    )}
                </View>
                <View variant="transparent" style={styles.info}>
                    <View variant="transparent" style={styles.nameRow}>
                        <Text variant="body" bold numberOfLines={1} style={{ flex: 1 }}>
                            {item.item_name}
                        </Text>
                        {item.seed != null && (
                            <Text variant="caption" color="tertiary" style={{ marginLeft: 6 }}>
                                #{item.seed}
                            </Text>
                        )}
                    </View>
                    <View variant="transparent" style={styles.metaRow}>
                        {item.bid_count != null && item.bid_count > 0 && (
                            <Text variant="caption" color="tertiary" style={{ fontSize: 11, lineHeight: 15 }}>
                                {item.bid_count} bidder{item.bid_count !== 1 ? 's' : ''}
                            </Text>
                        )}
                    </View>
                </View>
                <View variant="transparent" style={styles.bidCol}>
                    {hasBid ? (
                        <>
                            <Text variant="caption" color="tertiary" style={{ fontSize: 10, lineHeight: 13 }}>Your bid</Text>
                            <Text variant="body" bold style={{ color: theme.colors.status.success }}>
                                {formatCurrency(my_bid!.bid_amount, market_type)}
                            </Text>
                        </>
                    ) : canBidNow ? (
                        <View variant="transparent" style={[styles.bidCta, { backgroundColor: theme.colors.primary.subtle }]}>
                            <Text variant="caption" bold style={{ color: theme.colors.primary.default, fontSize: 11, lineHeight: 15 }}>
                                Place Bid
                            </Text>
                        </View>
                    ) : (
                        <Text variant="caption" color="tertiary" style={{ fontSize: 11, lineHeight: 15 }}>No bid</Text>
                    )}
                </View>
                {canBidNow && (
                    <Ionicons
                        name={expanded ? 'chevron-up' : 'chevron-down'}
                        size={14}
                        color={theme.colors.text.tertiary}
                        style={{ marginLeft: 6 }}
                    />
                )}
            </TouchableOpacity>

            {expanded && canBidNow && (
                <View variant="transparent" style={[styles.expandedArea, { borderColor: theme.colors.border.subtle }]}>
                    <View variant="transparent" style={styles.quickRow}>
                        {QUICK_AMOUNTS.map(amt => (
                            <TouchableOpacity
                                key={amt}
                                style={[styles.quickBtn, { backgroundColor: theme.colors.surface.base, borderColor: theme.colors.border.subtle }]}
                                onPress={() => onPlaceBid(amt)}
                                disabled={bidLoading}
                                activeOpacity={0.7}
                            >
                                <Text variant="caption" bold style={{ color: theme.colors.text.primary }}>
                                    {formatCurrency(amt, market_type)}
                                </Text>
                            </TouchableOpacity>
                        ))}
                    </View>
                    <CalcuttaBidInput
                        current_bid={item.current_bid}
                        min_bid={min_bid}
                        bid_increment={bid_increment}
                        auction_type="sealed_bid"
                        escrow_balance={escrow_balance}
                        existing_bid_amount={my_bid?.bid_amount}
                        onSubmit={onPlaceBid}
                        loading={bidLoading}
                        disabled={disabled}
                    />
                </View>
            )}
        </View>
    );
};

const styles = StyleSheet.create({
    card: {
        borderWidth: 1,
        borderRadius: 10,
        marginHorizontal: 12,
        marginBottom: 8,
        overflow: 'hidden',
    },
    row: {
        flexDirection: 'row',
        alignItems: 'center',
        padding: 12,
    },
    iconWrap: {
        width: 36,
        height: 36,
        borderRadius: 18,
        alignItems: 'center',
        justifyContent: 'center',
    },
    itemImage: {
        width: 36,
        height: 36,
        borderRadius: 18,
    },
    info: {
        flex: 1,
        marginLeft: 10,
    },
    nameRow: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    metaRow: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 2,
    },
    wonBadge: {
        paddingHorizontal: 6,
        paddingVertical: 2,
        borderRadius: 4,
    },
    bidCol: {
        alignItems: 'flex-end',
        marginLeft: 10,
    },
    bidCta: {
        paddingHorizontal: 10,
        paddingVertical: 5,
        borderRadius: 6,
    },
    lostBidRow: {
        paddingHorizontal: 12,
        paddingBottom: 10,
        borderTopWidth: 1,
        paddingTop: 8,
    },
    expandedArea: {
        borderTopWidth: 1,
        paddingHorizontal: 12,
        paddingBottom: 12,
    },
    quickRow: {
        flexDirection: 'row',
        paddingTop: 10,
        gap: 8,
    },
    quickBtn: {
        flex: 1,
        paddingVertical: 8,
        borderRadius: 6,
        borderWidth: 1,
        alignItems: 'center',
    },
});
