// formatCurrency should be loaded before this file
const formatCurrency = typeof window !== 'undefined' ? window.formatCurrency : (typeof require !== 'undefined' ? require('../utils/formatCurrency.js').formatCurrency : null);
const { useState, useRef } = React;

const lineUnitPrice = (item) => {
    if (typeof window !== 'undefined' && window.taxCalculator && typeof window.taxCalculator.getEffectiveUnitPrice === 'function') {
        return window.taxCalculator.getEffectiveUnitPrice(item);
    }
    const qty = parseFloat(item?.quantity ?? item?.tcount ?? 1) || 1;
    const pcount = Number(item?.pcount || 0);
    const price_big = Number(item?.price_big || 0);
    const retail = Number(item?.price_low ?? item?.price ?? 0) || 0;
    if (pcount > 0 && price_big > 0 && pcount <= qty) return price_big;
    return retail;
};

function Cart({ 
    cart, 
    onUpdateQuantity,
    onUpdateDiscount,
    onRemoveFromCart,
    onRemoveItem,
    onDiscountCardScan,
    onCheckout,
    calculateTotal, 
    calculateVATTotal,
    calculateCityTaxTotal,
    calculateTaxTotal,
    calculateDiscountTotal,
    calculateGrandTotal,
    cartSummary,
    showAlert,
    barcodeInputRef,
    barcodeInput,
    onBarcodeChange,
    onBarcodeScan,
    internalCodeInput,
    onInternalCodeChange,
    onInternalCodeSearch,
    selectedItemId,
    onItemSelect,
    onQuantityInputRequest,
    currentDiscountCard,
    onProductCatalogClick,
    onBeginNewPurchase,
    showConfirm,
    currentMtId,
    heldPurchases,
    onHoldPurchase,
    onResumeHeldPurchase
}) {
    const handleRemove = onRemoveItem || onRemoveFromCart;
    const [discountCardInput, setDiscountCardInput] = useState('');
    const discountCardBalance = currentDiscountCard?.cardBalance ?? currentDiscountCard?.card_balance;
    const discountCardTotal = currentDiscountCard?.discountTotal ?? currentDiscountCard?.discount_total;
    
    const discountCardInputRef = useRef(null);
    
    const handleDiscountCardKeyPress = async (e) => {
        if (e.key === 'Enter' && discountCardInput.trim()) {
            if (onDiscountCardScan) {
                const result = await onDiscountCardScan(discountCardInput.trim());
                // Зөвхөн амжилттай үед л input цэвэрлэх
                if (result && result.success) {
                    setDiscountCardInput('');
                } else {
                    // Буруу бол focus буцаах - alert-ийн дараа удаан хүлээх
                    const focusInput = () => {
                        if (discountCardInputRef.current) {
                            discountCardInputRef.current.focus();
                            // Cursor-ийг төгсгөлд байрлуулах
                            const length = discountCardInputRef.current.value.length;
                            discountCardInputRef.current.setSelectionRange(length, length);
                        }
                    };
                    // Олон удаа оролдох - alert modal focus-ийг авч байж магадгүй
                    setTimeout(focusInput, 300);
                    setTimeout(focusInput, 600);
                    setTimeout(focusInput, 1000);
                }
            }
        }
    };
    
    return (
        <div className="cart-section" data-cart-items={cart.length}>
            <div className="cart-header">
                <div>
                    <h2>Сагс</h2>
                    {cart.length > 0 && (
                        <div
                            style={{
                                fontSize: '11px',
                                color: '#856404',
                                marginTop: '4px',
                                fontWeight: '600'
                            }}
                            title="Төлбөр төлөх хүртэл энэ худалдан авалт идэвхтэй"
                        >
                            Тооцоо хийгээгүй — хүлээгдэж байна
                        </div>
                    )}
                </div>
            </div>

            <div style={{ 
                marginBottom: '10px', 
                padding: '8px', 
                background: '#e8f4f8', 
                borderRadius: '4px',
                border: '1px solid #b8d4e0'
            }}>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '10px', alignItems: 'flex-end' }}>
                    <div style={{ flex: '1', minWidth: '140px' }}>
                        <label style={{ display: 'block', fontSize: '11px', color: '#495057', marginBottom: '3px', fontWeight: 'bold' }}>Баркод:</label>
                        <input
                            ref={barcodeInputRef}
                            type="text"
                            value={barcodeInput != null ? barcodeInput : ''}
                            onChange={(e) => onBarcodeChange && onBarcodeChange(e.target.value)}
                            onKeyPress={(e) => { if (e.key === 'Enter' && barcodeInput && onBarcodeScan) onBarcodeScan(barcodeInput); }}
                            placeholder="Баркод уншуулах..."
                            style={{ width: '100%', padding: '6px 8px', border: '1px solid #667eea', borderRadius: '4px', fontSize: '12px' }}
                        />
                    </div>
                    <div style={{ flex: '1', minWidth: '140px' }}>
                        <label style={{ display: 'block', fontSize: '11px', color: '#495057', marginBottom: '3px', fontWeight: 'bold' }}>Дотоод код:</label>
                        <input
                            id="internalCodeInputCart"
                            type="text"
                            value={internalCodeInput != null ? internalCodeInput : ''}
                            onChange={(e) => onInternalCodeChange && onInternalCodeChange(e.target.value)}
                            onKeyPress={(e) => { if (e.key === 'Enter' && internalCodeInput && onInternalCodeSearch) onInternalCodeSearch(internalCodeInput); }}
                            placeholder="Дотоод код (dotcode)..."
                            style={{ width: '100%', padding: '6px 8px', border: '1px solid #667eea', borderRadius: '4px', fontSize: '12px' }}
                        />
                    </div>
                </div>
            </div>
            
            {cart.length > 0 && (
                <div style={{ 
                    marginBottom: '10px', 
                    padding: '8px', 
                    background: '#f8f9fa', 
                    borderRadius: '4px',
                    border: '1px solid #dee2e6'
                }}>
                    <label style={{ 
                        display: 'block', 
                        fontSize: '11px', 
                        color: '#495057', 
                        marginBottom: '4px',
                        fontWeight: 'bold'
                    }}>
                        Хөнгөлөлтийн карт:
                    </label>
                    {currentDiscountCard && (currentDiscountCard.cardNo || currentDiscountCard.card_no) && (
                        <div style={{ 
                            marginBottom: '6px', 
                            padding: '4px 8px', 
                            background: '#e8f5e9', 
                            borderRadius: '4px',
                            fontSize: '11px',
                            color: '#2e7d32'
                        }}>
                            <div style={{ fontWeight: 'bold' }}>
                                Карт: {currentDiscountCard.cardNo || currentDiscountCard.card_no}
                            </div>
                            {currentDiscountCard.owner && (
                                <div style={{ marginTop: '2px', fontSize: '10px' }}>
                                    Эзэмшгч: {currentDiscountCard.owner}
                                </div>
                            )}
                            {discountCardBalance !== null && discountCardBalance !== undefined && discountCardBalance !== '' && (
                                <div style={{ marginTop: '2px', fontSize: '10px' }}>
                                    Үлдэгдэл: {typeof discountCardBalance === 'number' && formatCurrency ? formatCurrency(discountCardBalance) : discountCardBalance}
                                </div>
                            )}
                            {discountCardTotal !== null && discountCardTotal !== undefined && discountCardTotal !== '' && (
                                <div style={{ marginTop: '2px', fontSize: '10px' }}>
                                    Худалдан авалтын дүн: {typeof discountCardTotal === 'number' && formatCurrency ? formatCurrency(discountCardTotal) : discountCardTotal}
                                </div>
                            )}
                        </div>
                    )}
                    <div style={{ display: 'flex', gap: '4px' }}>
                        <input
                            id="discountCardInput"
                            ref={discountCardInputRef}
                            type="text"
                            value={discountCardInput}
                            onChange={(e) => setDiscountCardInput(e.target.value)}
                            onKeyPress={handleDiscountCardKeyPress}
                            placeholder="Карт уншуулах..."
                            style={{
                                flex: 1,
                                padding: '6px',
                                border: '1px solid #ced4da',
                                borderRadius: '4px',
                                fontSize: '12px',
                                boxSizing: 'border-box'
                            }}
                            autoFocus={false}
                        />
                        <button
                            className="btn btn-secondary"
                            onClick={async () => {
                                if (discountCardInput.trim() && onDiscountCardScan) {
                                    const result = await onDiscountCardScan(discountCardInput.trim());
                                    // Зөвхөн амжилттай үед л input цэвэрлэх
                                    if (result && result.success) {
                                        setDiscountCardInput('');
                                    } else {
                                        // Буруу бол focus буцаах - alert-ийн дараа удаан хүлээх
                                        const focusInput = () => {
                                            if (discountCardInputRef.current) {
                                                discountCardInputRef.current.focus();
                                                // Cursor-ийг төгсгөлд байрлуулах
                                                const length = discountCardInputRef.current.value.length;
                                                discountCardInputRef.current.setSelectionRange(length, length);
                                            }
                                        };
                                        // Олон удаа оролдох - alert modal focus-ийг авч байж магадгүй
                                        setTimeout(focusInput, 300);
                                        setTimeout(focusInput, 600);
                                        setTimeout(focusInput, 1000);
                                    }
                                }
                            }}
                            style={{
                                padding: '6px 12px',
                                fontSize: '12px',
                                whiteSpace: 'nowrap'
                            }}
                        >
                            Уншуулах
                        </button>
                    </div>
                </div>
            )}

            <div className="cart-items">
                {cart.length === 0 ? (
                    <div className="empty-cart">
                        <div className="empty-cart-icon">🛒</div>
                        <p>Таны сагс хоосон байна</p>
                        <p>Бүтээгдэхүүн дээр дарж нэмнэ үү</p>
                    </div>
                ) : (
                    <>
                        {/* Header row */}
                        <div style={{ 
                            display: 'grid', 
                            gridTemplateColumns: '30px 50px 80px minmax(140px, 1fr) 60px 80px 100px 90px',
                            alignItems: 'center',
                            gap: '4px',
                            padding: '6px 4px',
                            borderBottom: '2px solid #667eea',
                            backgroundColor: '#f8f9fa',
                            fontWeight: 'bold',
                            fontSize: '10px',
                            color: '#2c3e50'
                        }}>
                            <div style={{ textAlign: 'center' }}>№</div>
                            <div style={{ textAlign: 'center' }}>Устгах</div>
                            <div style={{ textAlign: 'left' }}>Код</div>
                            <div style={{ textAlign: 'left', minWidth: '140px' }}>Нэр</div>
                            <div style={{ textAlign: 'center' }}>Хөнгөлөлт</div>
                            <div style={{ textAlign: 'right' }}>Үнэ</div>
                            <div style={{ textAlign: 'center' }}>Тоо</div>
                            <div style={{ textAlign: 'right' }}>Дүн</div>
                        </div>
                        {cart.slice().reverse().map((item, index) => {
                        const rowNo = cart.length - index; // Reverse order row number
                        return (
                            <div 
                                key={item.id} 
                                className="cart-item" 
                                onDoubleClick={(e) => {
                                    // Input field эсвэл button дээр double click хийхэд тоо оруулах цонх гаргахгүй
                                    if (e.target.tagName !== 'INPUT' && e.target.tagName !== 'BUTTON') {
                                        if (onQuantityInputRequest && typeof onQuantityInputRequest === 'function') {
                                            const currentQty = parseFloat(item.quantity || item.tcount || 1);
                                            const dotcode = item.dotcode || item.m_code || null;
                                            onQuantityInputRequest(item.id, currentQty, dotcode);
                                        }
                                    }
                                }}
                                style={{ 
                                    display: 'grid', 
                                    gridTemplateColumns: '30px 50px 80px minmax(140px, 1fr) 60px 80px 100px 90px',
                                    alignItems: 'center',
                                    gap: '4px',
                                    padding: '4px',
                                    borderBottom: '1px solid #e0e0e0',
                                    minHeight: '32px',
                                    cursor: 'default'
                                }}
                            >
                                <div style={{ 
                                    textAlign: 'center', 
                                    fontWeight: 'bold', 
                                    color: '#6c757d',
                                    fontSize: '10px'
                                }}>
                                    {rowNo}
                                </div>
                                <button
                                    className="remove-btn"
                                    onClick={() => handleRemove(item.id)}
                                    style={{
                                        padding: '4px 8px',
                                        fontSize: '11px',
                                        whiteSpace: 'nowrap',
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        gap: '4px',
                                        fontWeight: 'bold'
                                    }}
                                    title="Устгах"
                                >
                                    🗑️ Устгах
                                </button>
                                <div style={{ 
                                    fontSize: '10px',
                                    color: '#495057',
                                    overflow: 'hidden',
                                    textOverflow: 'ellipsis',
                                    whiteSpace: 'nowrap',
                                    textAlign: 'left'
                                }}>
                                    {item.dotcode || item.m_code || ''}
                                </div>
                                <div className="cart-item-name" style={{ 
                                    fontSize: '11px',
                                    fontWeight: 'bold',
                                    overflow: 'hidden',
                                    textOverflow: 'ellipsis',
                                    whiteSpace: 'nowrap',
                                    minWidth: '140px'
                                }}>
                                    {(item.shortname && item.shortname.trim() !== '') ? item.shortname : (item.name || item.m_name || 'Бүтээгдэхүүн')}
                                </div>
                                <div style={{ 
                                    textAlign: 'center', 
                                    fontSize: '10px',
                                    color: '#495057',
                                    fontWeight: 'bold',
                                    padding: '2px 4px'
                                }}>
                                    {formatCurrency ? formatCurrency(item.discount || 0) : ((item.discount || 0).toFixed(2))}
                                </div>
                                <div style={{ 
                                    textAlign: 'right', 
                                    fontSize: '10px',
                                    color: '#495057',
                                    fontWeight: 'bold'
                                }}>
                                    {formatCurrency ? formatCurrency(lineUnitPrice(item)) : (lineUnitPrice(item).toFixed(2))}
                                </div>
                                <div style={{ 
                                    textAlign: 'center', 
                                    fontSize: '10px',
                                    color: '#495057',
                                    fontWeight: 'bold',
                                    padding: '2px 4px'
                                }}>
                                    {(() => {
                                        const qty = parseFloat(item.quantity || item.tcount || 1);
                                        return isNaN(qty) ? '1' : qty.toString();
                                    })()}
                                </div>
                                <div className="item-total" style={{ 
                                    textAlign: 'right', 
                                    fontWeight: 'bold',
                                    fontSize: '11px'
                                }}>
                                    {formatCurrency(lineUnitPrice(item) * (item.quantity || item.tcount || 1) - (item.discount || 0))}
                                </div>
                            </div>
                        );
                    })}
                    </>
                )}
            </div>

            <div className="cart-footer cart-footer--slim">
                {cart.length > 0 && (
                    <div className="total-section" style={{ background: '#f8f9fa', marginBottom: '4px', padding: '4px 8px', borderRadius: '4px', border: '1px solid #dee2e6' }}>
                        <span className="total-label" style={{ fontWeight: 600, fontSize: '12px' }}>Нийт тоо хэмжээ:</span>
                        <span className="total-amount" style={{ fontWeight: 700, fontSize: '14px', color: '#2c3e50' }}>
                            {cart.reduce((sum, item) => sum + Math.round(item.quantity || item.tcount || 1), 0)}
                        </span>
                    </div>
                )}
                {cart.length > 0 && calculateVATTotal && calculateVATTotal() > 0 && (
                    <div className="total-section" style={{ background: '#e3f2fd', marginBottom: '4px', padding: '4px 8px', borderRadius: '4px', border: '1px solid #2196f3' }}>
                        <span className="total-label" style={{ color: '#1565c0', fontWeight: 600, fontSize: '12px' }}>НӨАТ:</span>
                        <span className="total-amount" style={{ color: '#1565c0', fontWeight: 700, fontSize: '14px' }}>
                            {formatCurrency(calculateVATTotal())}
                        </span>
                    </div>
                )}
                {cart.length > 0 && calculateCityTaxTotal && calculateCityTaxTotal() > 0 && (
                    <div className="total-section" style={{ background: '#f3e5f5', marginBottom: '4px', padding: '4px 8px', borderRadius: '4px', border: '1px solid #9c27b0' }}>
                        <span className="total-label" style={{ color: '#6a1b9a', fontWeight: 600, fontSize: '12px' }}>НХАТ:</span>
                        <span className="total-amount" style={{ color: '#6a1b9a', fontWeight: 700, fontSize: '14px' }}>
                            {formatCurrency(calculateCityTaxTotal())}
                        </span>
                    </div>
                )}
                {cart.length > 0 && calculateDiscountTotal && calculateDiscountTotal() > 0 && (
                    <div className="total-section" style={{ background: '#fff3cd', marginBottom: '4px', padding: '4px 8px', borderRadius: '4px', border: '1px solid #ffc107' }}>
                        <span className="total-label" style={{ color: '#856404', fontWeight: 600, fontSize: '12px' }}>Хөнгөлөлт:</span>
                        <span className="total-amount" style={{ color: '#856404', fontWeight: 700, fontSize: '14px' }}>
                            {formatCurrency(calculateDiscountTotal())}
                        </span>
                    </div>
                )}
                {cart.length > 0 && (
                    <div className="total-section" style={{ background: '#e8f5e9', marginBottom: '6px', padding: '4px 8px', borderRadius: '4px', border: '1px solid #c8e6c9' }}>
                        <span className="total-label" style={{ color: '#0d0d0d', fontWeight: 700, fontSize: '13px' }}>Нийт дүн:</span>
                        <span className="total-amount" style={{ color: '#000000', fontWeight: 800, fontSize: '17px', letterSpacing: '-0.02em' }}>
                            {formatCurrency(calculateGrandTotal())}
                        </span>
                    </div>
                )}
                <div className="checkout-buttons" style={{ display: 'flex', gap: '6px', flexDirection: 'column', width: '100%' }}>
                    {onHoldPurchase && cart.length > 0 && currentMtId && (
                        <button
                            type="button"
                            className="btn btn-secondary"
                            style={{
                                padding: '6px 10px',
                                fontSize: '12px',
                                lineHeight: 1.25,
                                fontWeight: 600,
                                background: '#17a2b8',
                                color: '#fff',
                                border: 'none'
                            }}
                            onClick={(e) => {
                                e.preventDefault();
                                onHoldPurchase();
                            }}
                            title="Одоогийн баримтыг баазаас бүү устгаж, дараагийн худалдан авалт руу шилжинэ"
                        >
                            Хүлээлгэх (баазад үлдээнэ)
                        </button>
                    )}
                    {heldPurchases && heldPurchases.length > 0 && onResumeHeldPurchase && (
                        <div style={{
                            width: '100%',
                            padding: '6px 8px',
                            background: '#e7f5f8',
                            borderRadius: '4px',
                            border: '1px solid #17a2b8',
                            marginBottom: '2px',
                            boxSizing: 'border-box'
                        }}>
                            <div style={{ fontSize: '11px', fontWeight: 600, color: '#0c5460', marginBottom: '4px' }}>
                                Хүлээлгэсэн худалдан авалт
                            </div>
                            {heldPurchases.map((h) => (
                                <div
                                    key={String(h.mt_id) + '_' + h.at}
                                    style={{
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'space-between',
                                        gap: '8px',
                                        marginBottom: '4px',
                                        fontSize: '11px'
                                    }}
                                >
                                    <span style={{ color: '#0c5460' }}>
                                        mt_id {h.mt_id}
                                        <span style={{ color: '#6c757d', marginLeft: '6px' }}>
                                            {new Date(h.at).toLocaleTimeString('mn-MN', { hour: '2-digit', minute: '2-digit' })}
                                        </span>
                                    </span>
                                    <button
                                        type="button"
                                        onClick={() => onResumeHeldPurchase(h.mt_id)}
                                        style={{
                                            padding: '4px 10px',
                                            fontSize: '11px',
                                            background: '#138496',
                                            color: '#fff',
                                            border: 'none',
                                            borderRadius: '4px',
                                            cursor: 'pointer',
                                            whiteSpace: 'nowrap'
                                        }}
                                    >
                                        Сэргээх
                                    </button>
                                </div>
                            ))}
                        </div>
                    )}
                    {onBeginNewPurchase && (
                        <button
                            type="button"
                            className="btn btn-secondary"
                            style={{
                                padding: '6px 10px',
                                fontSize: '12px',
                                lineHeight: 1.25,
                                fontWeight: 600,
                                background: '#6c757d',
                                color: '#fff',
                                border: 'none'
                            }}
                            onClick={(e) => {
                                e.preventDefault();
                                if (cart.length === 0) {
                                    onBeginNewPurchase();
                                    return;
                                }
                                if (showConfirm && typeof showConfirm === 'function') {
                                    showConfirm(
                                        'Одоогийн сагсанд тооцоо хийгээгүй (хүлээгдэж байгаа) бараа байна. Баазаас устгаж шинэ баримт (шинэ mt_id) эхлүүлэх үү? (Хүлээлгэх бол «Хүлээлгэх» товчийг ашиглана уу.)',
                                        () => onBeginNewPurchase()
                                    );
                                } else {
                                    onBeginNewPurchase();
                                }
                            }}
                        >
                            Шинэ худалдан авалт (цуцлах — мөр устгана)
                        </button>
                    )}
                    {cart.length > 0 && (
                        <button 
                            className="btn btn-primary"
                            style={{
                                padding: '6px 10px',
                                fontSize: '12px',
                                lineHeight: 1.25,
                                fontWeight: 600
                            }}
                            onClick={(e) => {
                                console.log('Checkout button clicked, onCheckout:', onCheckout);
                                e.preventDefault();
                                if (onCheckout) {
                                    onCheckout();
                                } else {
                                    console.error('onCheckout is not defined!');
                                    const message = 'Төлбөр төлөх функц олдсонгүй!';
                                    if (showAlert && typeof showAlert === 'function') {
                                        showAlert(message);
                                    }
                                }
                            }}
                        >
                            Төлбөр төлөх
                        </button>
                    )}
                </div>
            </div>
        </div>
    );
}

// Make available globally for browser
if (typeof window !== 'undefined') {
    window.Cart = Cart;
}

