import React, { useState, useEffect, useRef } 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 { formatCurrency, getStatusLabel, getItemStatusColor, getBidStatusColor } from '../helpers/formatting';
import { CalcuttaBidInput } from './CalcuttaBidInput';

export interface CalcuttaAuctionItemComponentProps {
    item: CalcuttaAuctionItemProps;
    my_bid?: CalcuttaBidProps;
    auction_type: 'sealed_bid' | 'live';
    min_bid: number;
    bid_increment: number;
    escrow_balance: number;
    onPlaceBid: (amount: number) => void;
    is_active_item?: boolean;
    is_paused?: boolean;
    itemImage?: { url: string };
    highest_bidder?: { username?: string; profile_pic?: string; is_me?: boolean };
    winner?: { username?: string; profile_pic?: string; is_me?: boolean };
}

const getTimerColor = (secondsLeft: number, theme: any) => {
    if (secondsLeft > 30) return theme.colors.status.success;
    if (secondsLeft > 10) return '#F59E0B'; // amber/yellow
    return theme.colors.status.error;
};

export const CalcuttaAuctionItem: React.FC<CalcuttaAuctionItemComponentProps> = ({
    item,
    my_bid,
    auction_type,
    min_bid,
    bid_increment,
    escrow_balance,
    onPlaceBid,
    is_active_item,
    is_paused,
    itemImage,
    highest_bidder,
    winner,
}) => {
    const { theme } = useTheme();
    const [expanded, setExpanded] = useState(!!is_active_item);

    // Auto-expand when this item becomes active
    useEffect(() => {
        if (is_active_item) setExpanded(true);
    }, [is_active_item]);

    // Per-item countdown for live auction
    const [secondsLeft, setSecondsLeft] = useState<number | null>(null);
    const countdownRef = useRef<ReturnType<typeof setInterval> | null>(null);

    useEffect(() => {
        if (countdownRef.current) clearInterval(countdownRef.current);
        setSecondsLeft(null);

        if (!item.item_deadline || item.status !== 'active' || is_paused) return;

        const updateTimer = () => {
            const deadline = new Date(item.item_deadline).getTime();
            const diff = Math.max(0, (deadline - Date.now()) / 1000);
            setSecondsLeft(diff);
            if (diff <= 0 && countdownRef.current) {
                clearInterval(countdownRef.current);
            }
        };

        updateTimer();
        countdownRef.current = setInterval(updateTimer, 100);
        return () => {
            if (countdownRef.current) clearInterval(countdownRef.current);
        };
    }, [item.item_deadline, item.status, is_paused]);

    const canBid = auction_type === 'live'
        ? item.status === 'active' && is_active_item && !is_paused
        : (item.status === 'active' || item.status === 'pending') && !is_paused;
    const statusColor = getItemStatusColor(item.status);
    const isSold = item.status === 'sold';
    const isUpcoming = auction_type === 'live' && item.status === 'pending';
    const itemOpacity = (isSold || item.status === 'unsold') ? 0.5 : isUpcoming ? 0.7 : 1;

    // Format seconds to display
    const formatCountdown = (s: number) => {
        if (s >= 60) {
            const min = Math.floor(s / 60);
            const sec = Math.floor(s % 60);
            return `${min}:${sec.toString().padStart(2, '0')}`;
        }
        return s.toFixed(1);
    };

    // ══════════════════════════════════════
    // ACTIVE ITEM — hero card, always expanded
    // ══════════════════════════════════════
    if (is_active_item && auction_type === 'live') {
        const timerColor = secondsLeft != null && secondsLeft > 0 ? getTimerColor(secondsLeft, theme) : theme.colors.text.tertiary;
        const isUrgent = secondsLeft != null && secondsLeft <= 10 && secondsLeft > 0;

        return (
            <View variant="transparent" style={[styles.activeCard, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.primary.default + '40' }]}>
                {/* Top bar: item info + timer */}
                <View variant="transparent" style={styles.activeHeader}>
                    {(itemImage?.url || item.item_image?.url) ? (
                        <Image
                            source={{ uri: itemImage?.url || item.item_image?.url }}
                            style={[styles.activeImage, { backgroundColor: theme.colors.surface.base }]}
                            resizeMode="contain"
                        />
                    ) : (
                        <View variant="transparent" style={[styles.activeImage, { backgroundColor: theme.colors.surface.base }]}>
                            <Ionicons
                                name={item.item_type === 'team' ? 'people-outline' : 'person-outline'}
                                size={24}
                                color={theme.colors.text.tertiary}
                            />
                        </View>
                    )}
                    <View variant="transparent" style={{ flex: 1, marginLeft: 14 }}>
                        <Text variant="h3" bold numberOfLines={1}>{item.item_name}</Text>
                        {item.seed != null && <Text variant="caption" color="tertiary">Seed #{item.seed}</Text>}
                        {highest_bidder && item.current_bid > 0 && (
                            <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', marginTop: 4 }}>
                                {highest_bidder.profile_pic ? (
                                    <Image source={{ uri: highest_bidder.profile_pic }} style={{ width: 16, height: 16, borderRadius: 8, marginRight: 5 }} />
                                ) : (
                                    <View variant="transparent" style={{ width: 16, height: 16, borderRadius: 8, backgroundColor: highest_bidder.is_me ? '#10B98130' : theme.colors.primary.subtle, alignItems: 'center', justifyContent: 'center', marginRight: 5 }}>
                                        <Text variant="caption" style={{ fontSize: 8, lineHeight: 11, color: highest_bidder.is_me ? '#10B981' : theme.colors.primary.default }}>
                                            {(highest_bidder.username || '?').charAt(0).toUpperCase()}
                                        </Text>
                                    </View>
                                )}
                                <Text variant="caption" style={{ color: highest_bidder.is_me ? '#10B981' : theme.colors.text.secondary, fontSize: 12, lineHeight: 16 }}>
                                    {highest_bidder.is_me ? 'You' : highest_bidder.username || 'Unknown'}
                                </Text>
                                {highest_bidder.is_me && (
                                    <Ionicons name="checkmark-circle" size={12} color="#10B981" style={{ marginLeft: 3 }} />
                                )}
                            </View>
                        )}
                    </View>
                </View>

                {/* Current bid + highest bidder + timer row */}
                <View variant="transparent" style={styles.activeBidRow}>
                    <View variant="transparent" style={{ flex: 1 }}>
                        <Text variant="caption" color="tertiary">Current Bid</Text>
                        <Text style={[styles.activeBidAmount, { color: theme.colors.text.primary }]}>
                            {item.current_bid > 0 ? formatCurrency(item.current_bid) : 'No bids yet'}
                        </Text>
                    </View>
                    {secondsLeft != null && secondsLeft > 0 && !is_paused && (
                        <View variant="transparent" style={[styles.activeTimerBox, { backgroundColor: timerColor + '15', borderColor: timerColor + '30' }]}>
                            <Ionicons name="timer-outline" size={16} color={timerColor} />
                            <Text style={[styles.activeTimerText, { color: timerColor }]}>
                                {formatCountdown(secondsLeft)}
                            </Text>
                            {isUrgent && item.current_bid > 0 && (
                                <Text variant="caption" bold style={{ color: theme.colors.status.error, marginLeft: 6, fontSize: 11, lineHeight: 15 }}>
                                    Going!
                                </Text>
                            )}
                        </View>
                    )}
                </View>

                {/* Bid input — always visible */}
                {canBid && (
                    <CalcuttaBidInput
                        current_bid={item.current_bid}
                        min_bid={min_bid}
                        bid_increment={bid_increment}
                        auction_type={auction_type}
                        escrow_balance={escrow_balance}
                        existing_bid_amount={my_bid?.bid_amount}
                        onSubmit={onPlaceBid}
                        loading={false}
                        disabled={is_paused}
                    />
                )}
            </View>
        );
    }

    // ══════════════════════════════════════
    // INACTIVE ITEMS — compact rows
    // ══════════════════════════════════════
    return (
        <View
            variant="transparent"
            style={[
                styles.container,
                { borderColor: theme.colors.border.subtle, opacity: itemOpacity, backgroundColor: theme.colors.surface.base },
            ]}
        >
            <TouchableOpacity
                style={styles.row}
                activeOpacity={canBid ? 0.7 : 1}
                onPress={() => canBid && setExpanded(!expanded)}
                disabled={!canBid}
            >
                {(itemImage?.url || item.item_image?.url) ? (
                    <Image
                        source={{ uri: itemImage?.url || item.item_image?.url }}
                        style={[styles.imageContainer, { backgroundColor: theme.colors.surface.elevated }]}
                        resizeMode="contain"
                    />
                ) : (
                    <View variant="transparent" style={[styles.imageContainer, { backgroundColor: theme.colors.surface.elevated }]}>
                        <Ionicons
                            name={item.item_type === 'team' ? 'people-outline' : 'person-outline'}
                            size={16}
                            color={theme.colors.text.tertiary}
                        />
                    </View>
                )}

                <View variant="transparent" style={styles.info}>
                    <Text variant="body" bold numberOfLines={1}>{item.item_name}{item.seed != null ? ` #${item.seed}` : ''}</Text>
                    <View variant="transparent" style={styles.statusRow}>
                        <View variant="transparent" style={[styles.statusBadge, { backgroundColor: statusColor + '20' }]}>
                            <Text variant="caption" style={{ color: statusColor, fontSize: 10, lineHeight: 13 }}>{getStatusLabel(item.status)}</Text>
                        </View>
                        {my_bid && (
                            <View variant="transparent" style={styles.bidStatus}>
                                <Ionicons name={my_bid.bid_status === 'won' ? 'checkmark-circle' : 'ellipse'} size={10} color={getBidStatusColor(my_bid.bid_status)} />
                                <Text variant="caption" style={{ color: getBidStatusColor(my_bid.bid_status), marginLeft: 3, fontSize: 10, lineHeight: 13 }}>{getStatusLabel(my_bid.bid_status)}</Text>
                            </View>
                        )}
                        {isSold && item.winning_bid > 0 && (
                            <Text variant="caption" color="tertiary" style={{ marginLeft: 6, fontSize: 10, lineHeight: 13 }}>Sold: {formatCurrency(item.winning_bid)}</Text>
                        )}
                        {isSold && winner && (
                            <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', marginLeft: 6 }}>
                                {winner.profile_pic ? (
                                    <Image source={{ uri: winner.profile_pic }} style={{ width: 14, height: 14, borderRadius: 7, marginRight: 3 }} />
                                ) : (
                                    <View variant="transparent" style={{ width: 14, height: 14, borderRadius: 7, backgroundColor: winner.is_me ? '#10B98130' : theme.colors.primary.subtle, alignItems: 'center', justifyContent: 'center', marginRight: 3 }}>
                                        <Text variant="caption" style={{ fontSize: 7, lineHeight: 10, color: winner.is_me ? '#10B981' : theme.colors.primary.default }}>
                                            {(winner.username || '?').charAt(0).toUpperCase()}
                                        </Text>
                                    </View>
                                )}
                                <Text variant="caption" style={{ fontSize: 10, lineHeight: 13, color: winner.is_me ? '#10B981' : theme.colors.text.tertiary }}>
                                    {winner.is_me ? 'You' : winner.username || 'Unknown'}
                                </Text>
                            </View>
                        )}
                    </View>
                </View>

                <View variant="transparent" style={styles.rightColumn}>
                    <Text variant="caption" color="tertiary" style={{ fontSize: 10, lineHeight: 13 }}>
                        {auction_type === 'sealed_bid' ? 'Your Bid' : isSold ? 'Winning Bid' : 'Current Bid'}
                    </Text>
                    <Text variant="body" bold>
                        {auction_type === 'sealed_bid'
                            ? my_bid ? formatCurrency(my_bid.bid_amount) : '-'
                            : (isSold ? item.winning_bid : item.current_bid) > 0 ? formatCurrency(isSold ? item.winning_bid : item.current_bid) : '-'}
                    </Text>
                    {canBid && <Ionicons name={expanded ? 'chevron-up' : 'chevron-down'} size={14} color={theme.colors.text.tertiary} style={{ marginTop: 2 }} />}
                </View>
            </TouchableOpacity>

            {expanded && canBid && (
                <View variant="transparent" style={[styles.bidInputContainer, { borderColor: theme.colors.border.subtle }]}>
                    <CalcuttaBidInput
                        current_bid={item.current_bid}
                        min_bid={min_bid}
                        bid_increment={bid_increment}
                        auction_type={auction_type}
                        escrow_balance={escrow_balance}
                        existing_bid_amount={my_bid?.bid_amount}
                        onSubmit={onPlaceBid}
                        loading={false}
                        disabled={is_paused}
                    />
                </View>
            )}
        </View>
    );
};

const styles = StyleSheet.create({
    // ── Active item hero card ──
    activeCard: {
        marginHorizontal: 12,
        marginVertical: 8,
        borderRadius: 16,
        borderWidth: 1.5,
        padding: 16,
    },
    activeHeader: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    activeImage: {
        width: 52,
        height: 52,
        borderRadius: 12,
        alignItems: 'center',
        justifyContent: 'center',
    },
    activeBidRow: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 14,
        paddingTop: 14,
        borderTopWidth: 1,
        borderTopColor: 'rgba(128,128,128,0.15)',
    },
    activeBidAmount: {
        fontSize: 28,
        lineHeight: 37,
        fontWeight: '800',
        marginTop: 2,
    },
    activeTimerBox: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 12,
        paddingVertical: 8,
        borderRadius: 10,
        borderWidth: 1,
    },
    activeTimerText: {
        fontSize: 20,
        lineHeight: 26,
        fontWeight: '800',
        marginLeft: 6,
    },
    // ── Inactive item rows ──
    container: {
        borderBottomWidth: 1,
    },
    row: {
        flexDirection: 'row',
        alignItems: 'center',
        padding: 12,
    },
    imageContainer: {
        height: 36,
        width: 36,
        borderRadius: 8,
        alignItems: 'center',
        justifyContent: 'center',
    },
    info: {
        flex: 1,
        marginLeft: 10,
        marginRight: 10,
    },
    statusRow: {
        flexDirection: 'row',
        alignItems: 'center',
        flexWrap: 'wrap',
        marginTop: 3,
    },
    statusBadge: {
        paddingHorizontal: 6,
        paddingVertical: 2,
        borderRadius: 4,
    },
    bidStatus: {
        flexDirection: 'row',
        alignItems: 'center',
        marginLeft: 6,
    },
    rightColumn: {
        alignItems: 'flex-end',
        minWidth: 70,
    },
    bidInputContainer: {
        paddingHorizontal: 12,
        paddingBottom: 12,
        borderTopWidth: 1,
    },
});
