import React, { useState, useEffect } from 'react';
import { StyleSheet, TextInput, TouchableOpacity, ActivityIndicator } from 'react-native';
import { View, Text, useTheme } from '@bettoredge/styles';
import { Ionicons } from '@expo/vector-icons';
import { formatCurrency } from '../helpers/formatting';

export interface CalcuttaBidInputProps {
    current_bid: number;
    min_bid: number;
    bid_increment: number;
    auction_type: 'sealed_bid' | 'live';
    escrow_balance: number;
    existing_bid_amount?: number;
    onSubmit: (amount: number) => void | Promise<void>;
    loading: boolean;
    disabled?: boolean;
}

export const CalcuttaBidInput: React.FC<CalcuttaBidInputProps> = ({
    current_bid,
    min_bid,
    bid_increment,
    auction_type,
    escrow_balance,
    existing_bid_amount,
    onSubmit,
    loading,
    disabled,
}) => {
    const { theme } = useTheme();

    const minimumAllowed = auction_type === 'live'
        ? Math.max(Number(min_bid), Number(current_bid) + Number(bid_increment))
        : Number(min_bid);

    const step = Number(bid_increment) > 0 ? Number(bid_increment) : 1;
    const available = escrow_balance;
    const isHighestBidder = existing_bid_amount != null && existing_bid_amount >= Number(current_bid) && Number(current_bid) > 0;
    const [raise, setRaise] = useState(0);
    const [error, setError] = useState('');
    const [submitting, setSubmitting] = useState(false);

    // Total bid = minimum + raise
    const totalBid = minimumAllowed + raise;
    const canAfford = totalBid <= available;

    // Reset raise when minimum changes (new bid came in)
    useEffect(() => {
        setRaise(0);
    }, [minimumAllowed]);

    const handleSubmit = async () => {
        if (!canAfford) {
            setError(`Insufficient escrow. Available: ${formatCurrency(available)}`);
            return;
        }
        setSubmitting(true);
        setError('');
        try {
            await onSubmit(totalBid);
            setRaise(0);
        } catch (e: any) {
            setError(e?.message || 'Failed to place bid');
        }
        setSubmitting(false);
    };

    const bumpUp = () => {
        const next = raise + step;
        if (minimumAllowed + next <= available) {
            setRaise(next);
            setError('');
        }
    };

    const bumpDown = () => {
        const next = raise - step;
        setRaise(Math.max(0, next));
        setError('');
    };

    return (
        <View variant="transparent" style={styles.container}>
            {disabled ? (
                <View variant="transparent" style={[styles.bidButton, { backgroundColor: theme.colors.surface.base }]}>
                    <Text variant="body" bold style={{ color: theme.colors.text.tertiary }}>Paused</Text>
                </View>
            ) : isHighestBidder ? (
                <View variant="transparent" style={[styles.highestBidder, { backgroundColor: '#10B98115' }]}>
                    <Ionicons name="checkmark-circle" size={20} color="#10B981" />
                    <View variant="transparent" style={{ marginLeft: 10, flex: 1 }}>
                        <Text variant="body" bold style={{ color: '#10B981' }}>You're the highest bidder</Text>
                        <Text variant="caption" color="secondary">
                            Your bid: {formatCurrency(existing_bid_amount)} · {formatCurrency(available)} available to raise
                        </Text>
                    </View>
                </View>
            ) : (
                <>
                    {/* Raise adjuster row */}
                    <View variant="transparent" style={styles.raiseRow}>
                        <TouchableOpacity
                            style={[styles.adjustBtn, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle, opacity: raise <= 0 ? 0.4 : 1 }]}
                            onPress={bumpDown}
                            disabled={raise <= 0}
                            activeOpacity={0.7}
                        >
                            <Ionicons name="remove" size={20} color={theme.colors.text.primary} />
                        </TouchableOpacity>

                        <View variant="transparent" style={styles.raiseDisplay}>
                            {raise > 0 ? (
                                <Text variant="caption" color="secondary">+{formatCurrency(raise)} more</Text>
                            ) : (
                                <Text variant="caption" color="tertiary">Minimum bid</Text>
                            )}
                            <Text variant="h3" bold>{formatCurrency(totalBid)}</Text>
                        </View>

                        <TouchableOpacity
                            style={[styles.adjustBtn, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle, opacity: (minimumAllowed + raise + step > available) ? 0.4 : 1 }]}
                            onPress={bumpUp}
                            disabled={minimumAllowed + raise + step > available}
                            activeOpacity={0.7}
                        >
                            <Ionicons name="add" size={20} color={theme.colors.text.primary} />
                        </TouchableOpacity>
                    </View>

                    {/* Bid button */}
                    <TouchableOpacity
                        style={[styles.bidButton, { backgroundColor: canAfford ? theme.colors.primary.default : theme.colors.surface.elevated }]}
                        onPress={handleSubmit}
                        disabled={submitting || !canAfford}
                        activeOpacity={0.7}
                    >
                        {submitting ? (
                            <ActivityIndicator size="small" color="#FFFFFF" />
                        ) : (
                            <Text variant="body" bold style={{ color: canAfford ? '#FFFFFF' : theme.colors.text.tertiary }}>
                                {existing_bid_amount ? 'Raise to' : 'Place Bid'} {formatCurrency(totalBid)}
                            </Text>
                        )}
                    </TouchableOpacity>

                    {/* Available */}
                    <Text variant="caption" color="tertiary" style={{ marginTop: 4, textAlign: 'center' }}>
                        {formatCurrency(available)} available
                    </Text>
                </>
            )}

            {/* Error */}
            {error !== '' && (
                <View variant="transparent" style={[styles.errorRow, { backgroundColor: theme.colors.status.error + '10' }]}>
                    <Ionicons name="alert-circle" size={14} color={theme.colors.status.error} />
                    <Text variant="caption" style={{ color: theme.colors.status.error, marginLeft: 6, flex: 1 }}>{error}</Text>
                </View>
            )}
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        paddingTop: 8,
    },
    raiseRow: {
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 8,
    },
    adjustBtn: {
        width: 44,
        height: 44,
        borderRadius: 10,
        borderWidth: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    raiseDisplay: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    bidButton: {
        height: 46,
        borderRadius: 10,
        alignItems: 'center',
        justifyContent: 'center',
    },
    highestBidder: {
        flexDirection: 'row',
        alignItems: 'center',
        padding: 14,
        borderRadius: 10,
    },
    errorRow: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 6,
        padding: 8,
        borderRadius: 8,
    },
});
