import React, { useState, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { getAssetPath } from '../../utils/assetPath';
import { getTranslatedText } from '../../utils/i18nUtils';
import './CombatInventoryModal.css';
import { ItemStatBadges } from '../common/ItemStatBadges';
import { GameButton } from '../common/GameButton';

interface CombatInventoryModalProps {
    isOpen: boolean;
    onClose: () => void;
    onUseItem: (itemId: string) => void;
    inventory: any[];
}

export const CombatInventoryModal: React.FC<CombatInventoryModalProps> = ({
    isOpen,
    onClose,
    onUseItem,
    inventory
}) => {
    const { t } = useTranslation();
    const [searchTerm, setSearchTerm] = useState('');

    const combatItems = useMemo(() => {
        if (!inventory) return [];

        return inventory.filter(item => {
            // Check if item is usable in combat
            // If explicit combat_usable flag is present, respect it.
            // If not, fallback to 'consumable' type check, but ideally we want explicit flags.
            // Some items might be consumable but not combat usable (e.g. quest items, or long-cast items)
            // For now, checks: combat_usable OR (consumable AND has effects)

            const isCombatUsable = item.combat_usable === true;
            const isConsumable = item.type === 'consumable' || item.category === 'consumable' || item.consumable === true;

            // Allow if strictly combat_usable, or if consumable and not explicitly restricted
            const allowed = isCombatUsable || (isConsumable && item.combat_only !== false);

            const itemName = getTranslatedText(item.name).toLowerCase();
            const matchesSearch = itemName.includes(searchTerm.toLowerCase());

            return allowed && matchesSearch && item.quantity > 0;
        });
    }, [inventory, searchTerm]);

    if (!isOpen) return null;

    return (
        <div className="modal-backdrop" onClick={onClose}>
            <div className="combat-inventory-modal" onClick={e => e.stopPropagation()}>
                <div className="modal-header">
                    <h3>{t('combat.modal.supplies_title')}</h3>
                    <GameButton variant="danger" size="sm" onClick={onClose}>×</GameButton>
                </div>

                <div className="modal-body">
                    <div className="game-search-container" style={{ marginBottom: '1.5rem' }}>
                        <span className="game-search-icon">🔍</span>
                        <input
                            type="text"
                            className="game-search-input"
                            placeholder={t('combat.modal.search_items')}
                            value={searchTerm}
                            onChange={e => setSearchTerm(e.target.value)}
                            autoFocus
                        />
                    </div>

                    <div className="items-list">
                        {combatItems.length === 0 ? (
                            <div className="no-items">
                                <span style={{ fontSize: '3rem', opacity: 0.5 }}>📦</span>
                                {t('combat.modal.no_combat_items')}
                            </div>
                        ) : (
                            combatItems.map((item, index) => (
                                <div key={`${item.item_id}-${index}`} className="combat-item-card" onClick={() => onUseItem(item.item_id)}>
                                    {/* Image Section */}
                                    <div className="item-image-section">
                                        {item.image_path ? (
                                            <img
                                                src={getAssetPath(item.image_path)}
                                                alt={getTranslatedText(item.name)}
                                                className="item-img-thumb"
                                                onError={(e) => {
                                                    (e.target as HTMLImageElement).style.display = 'none';
                                                    const icon = (e.target as HTMLImageElement).nextElementSibling;
                                                    if (icon) icon.classList.remove('hidden');
                                                }}
                                            />
                                        ) : null}
                                        <div className={`item-icon-large ${item.tier ? `tier-${item.tier}` : 'tier-0'} ${item.image_path ? 'hidden' : ''}`}>
                                            {item.emoji || '📦'}
                                        </div>
                                        {item.quantity > 1 && <div className="item-quantity-badge">x{item.quantity}</div>}
                                    </div>

                                    {/* Info Section */}
                                    <div className="item-details">
                                        <h4 className={`item-name text-tier-${item.tier || 0}`}>
                                            {getTranslatedText(item.name)}
                                        </h4>
                                        {item.description && (
                                            <p className="item-description">{getTranslatedText(item.description)}</p>
                                        )}

                                        <div className="item-effects">
                                            {/* Shared stat badges */}
                                            <ItemStatBadges item={item} />

                                            {/* Combat-specific Effects (Throwables, etc) */}
                                            {item.combat_effects?.damage_min && (
                                                <span className="stat-badge damage">
                                                    💥 {item.combat_effects.damage_min}-{item.combat_effects.damage_max} Dmg
                                                </span>
                                            )}
                                            {item.combat_effects?.status && (
                                                <span className="stat-badge damage">
                                                    ☠️ {t(`effects.${item.combat_effects.status.name}`, item.combat_effects.status.name) as string}
                                                </span>
                                            )}
                                        </div>
                                    </div>

                                    {/* Action Button */}
                                    <GameButton variant="success" size="sm" style={{ flexShrink: 0 }}>
                                        {t('game.use')}
                                    </GameButton>
                                </div>
                            ))
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
};
