import { MouseEvent, ChangeEvent } from 'react'
import { PlayerState, Profile, Equipment } from './types'
import './InventoryModal.css'

interface InventoryModalProps {
    playerState: PlayerState
    profile: Profile
    equipment?: Equipment
    inventoryFilter: string
    inventoryCategoryFilter: string
    onClose: () => void
    onSetInventoryFilter: (filter: string) => void
    onSetInventoryCategoryFilter: (category: string) => void
    onUseItem: (itemId: number, invId: number) => void
    onEquipItem: (invId: number) => void
    onUnequipItem: (slot: string) => void
    onDropItem: (itemId: number, invId: number, quantity: number) => void
}

function InventoryModal({
    playerState,
    profile,
    equipment,
    inventoryFilter,
    inventoryCategoryFilter,
    onClose,
    onSetInventoryFilter,
    onSetInventoryCategoryFilter,
    onUseItem,
    onEquipItem,
    onUnequipItem,
    onDropItem
}: InventoryModalProps) {
    // Categories for the sidebar
    const categories = [
        { id: 'all', label: 'All Items', icon: '🎒' },
        { id: 'weapon', label: 'Weapons', icon: '⚔️' },
        { id: 'armor', label: 'Armor', icon: '🛡️' },
        { id: 'clothing', label: 'Clothing', icon: '👕' },
        { id: 'backpack', label: 'Backpacks', icon: '🎒' },
        { id: 'tool', label: 'Tools', icon: '🛠️' },
        { id: 'consumable', label: 'Consumables', icon: '🍖' },
        { id: 'resource', label: 'Resources', icon: '📦' },
        { id: 'quest', label: 'Quest', icon: '📜' },
        { id: 'misc', label: 'Misc', icon: '📦' }
    ]

    // Use inventory directly as it now includes equipped items
    const allItems = playerState.inventory;

    // Filter items based on search and category
    const filteredItems = allItems
        .filter((item: any) => {
            const itemName = item.name || 'Unknown Item';
            const matchesSearch = itemName.toLowerCase().includes(inventoryFilter.toLowerCase())
            const matchesCategory = inventoryCategoryFilter === 'all' || item.type === inventoryCategoryFilter
            return matchesSearch && matchesCategory
        })
        .sort((a: any, b: any) => {
            // Equipped items first
            if (a.is_equipped && !b.is_equipped) return -1;
            if (!a.is_equipped && b.is_equipped) return 1;
            return (a.name || '').localeCompare(b.name || '');
        })

    const renderItemCard = (item: any, i: number) => {
        const maxDurability = item.max_durability;
        const currentDurability = item.durability;

        const hasDurability = maxDurability && maxDurability > 0;

        return (
            <div key={i} className={`inventory-item-card compact ${item.is_equipped ? 'equipped' : ''}`}>
                {/* Left: Image/Icon */}
                <div className="item-image-section small">
                    {item.image_path ? (
                        <img
                            src={item.image_path}
                            alt={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}` : ''} ${item.image_path ? 'hidden' : ''}`}>
                        {item.emoji || '📦'}
                    </div>
                    {item.quantity > 1 && <div className="item-quantity-badge">x{item.quantity}</div>}
                </div>

                {/* Center: Info & Stats */}
                <div className="item-info-section">
                    <div className="item-header-compact">
                        <span className="item-emoji-inline">{item.emoji}</span>
                        <h4 className={`item-name-compact text-tier-${item.tier || 0}`}>{item.name}</h4>
                        {item.is_equipped && <span className="item-card-equipped">Equipped</span>}
                    </div>

                    <div className="item-stats-row">
                        {/* Fixed Weight/Volume Column */}
                        <div className="stat-group-fixed">
                            <div className="stat-row-compact">
                                <span>⚖️</span>
                                <span>{item.weight}kg</span>
                                {item.quantity > 1 && <span className="text-muted">| {(item.weight * item.quantity).toFixed(1)}kg</span>}
                            </div>
                            <div className="stat-row-compact">
                                <span>📦</span>
                                <span>{item.volume}L</span>
                                {item.quantity > 1 && <span className="text-muted">| {(item.volume * item.quantity).toFixed(1)}L</span>}
                            </div>
                        </div>

                        {/* Stats & Durability */}
                        <div className="stats-durability-column">
                            {item.description && <p className="item-description-compact">{item.description}</p>}

                            {/* Stats Row - Button-like Badges */}
                            <div className="stat-badges-container">
                                {/* Capacity */}
                                {(item.unique_stats?.weight_capacity || item.stats?.weight_capacity) && (
                                    <span className="stat-badge capacity">
                                        ⚖️ +{item.unique_stats?.weight_capacity || item.stats?.weight_capacity}kg
                                    </span>
                                )}
                                {(item.unique_stats?.volume_capacity || item.stats?.volume_capacity) && (
                                    <span className="stat-badge capacity">
                                        📦 +{item.unique_stats?.volume_capacity || item.stats?.volume_capacity}L
                                    </span>
                                )}

                                {/* Combat */}
                                {(item.unique_stats?.damage_min || item.stats?.damage_min) && (
                                    <span className="stat-badge damage">
                                        ⚔️ {item.unique_stats?.damage_min || item.stats?.damage_min}-{item.unique_stats?.damage_max || item.stats?.damage_max}
                                    </span>
                                )}
                                {(item.unique_stats?.armor || item.stats?.armor) && (
                                    <span className="stat-badge armor">
                                        🛡️ +{item.unique_stats?.armor || item.stats?.armor}
                                    </span>
                                )}
                                {(item.unique_stats?.armor_penetration || item.stats?.armor_penetration) && (
                                    <span className="stat-badge penetration">
                                        💔 +{item.unique_stats?.armor_penetration || item.stats?.armor_penetration} Pen
                                    </span>
                                )}
                                {(item.unique_stats?.crit_chance || item.stats?.crit_chance) && (
                                    <span className="stat-badge crit">
                                        🎯 +{Math.round((item.unique_stats?.crit_chance || item.stats?.crit_chance) * 100)}% Crit
                                    </span>
                                )}
                                {(item.unique_stats?.accuracy || item.stats?.accuracy) && (
                                    <span className="stat-badge accuracy">
                                        👁️ +{Math.round((item.unique_stats?.accuracy || item.stats?.accuracy) * 100)}% Acc
                                    </span>
                                )}
                                {(item.unique_stats?.dodge_chance || item.stats?.dodge_chance) && (
                                    <span className="stat-badge dodge">
                                        💨 +{Math.round((item.unique_stats?.dodge_chance || item.stats?.dodge_chance) * 100)}% Dodge
                                    </span>
                                )}
                                {(item.unique_stats?.lifesteal || item.stats?.lifesteal) && (
                                    <span className="stat-badge lifesteal">
                                        🧛 +{Math.round((item.unique_stats?.lifesteal || item.stats?.lifesteal) * 100)}% Life
                                    </span>
                                )}

                                {/* Attributes */}
                                {(item.unique_stats?.strength_bonus || item.stats?.strength_bonus) && (
                                    <span className="stat-badge strength">
                                        💪 +{item.unique_stats?.strength_bonus || item.stats?.strength_bonus} STR
                                    </span>
                                )}
                                {(item.unique_stats?.agility_bonus || item.stats?.agility_bonus) && (
                                    <span className="stat-badge agility">
                                        🏃 +{item.unique_stats?.agility_bonus || item.stats?.agility_bonus} AGI
                                    </span>
                                )}
                                {(item.unique_stats?.endurance_bonus || item.stats?.endurance_bonus) && (
                                    <span className="stat-badge endurance">
                                        🏋️ +{item.unique_stats?.endurance_bonus || item.stats?.endurance_bonus} END
                                    </span>
                                )}
                                {(item.unique_stats?.hp_bonus || item.stats?.hp_bonus) && (
                                    <span className="stat-badge health">
                                        ❤️ +{item.unique_stats?.hp_bonus || item.stats?.hp_bonus} HP max
                                    </span>
                                )}
                                {(item.unique_stats?.stamina_bonus || item.stats?.stamina_bonus) && (
                                    <span className="stat-badge stamina">
                                        ⚡ +{item.unique_stats?.stamina_bonus || item.stats?.stamina_bonus} Stm max
                                    </span>
                                )}

                                {/* Consumables */}
                                {item.hp_restore && (
                                    <span className="stat-badge health">
                                        ❤️ +{item.hp_restore} HP
                                    </span>
                                )}
                                {item.stamina_restore && (
                                    <span className="stat-badge stamina">
                                        ⚡ +{item.stamina_restore} Stm
                                    </span>
                                )}
                            </div>

                            {/* Durability Bar */}
                            {hasDurability && (
                                <div className="durability-container">
                                    <div className="durability-header">
                                        <span>Durability</span>
                                        <span className={
                                            currentDurability < maxDurability * 0.2
                                                ? "durability-text-low"
                                                : ""
                                        }>
                                            {currentDurability} / {maxDurability}
                                        </span>
                                    </div>
                                    <div className="durability-track">
                                        <div
                                            className={`durability-fill ${currentDurability < maxDurability * 0.2
                                                ? "low"
                                                : currentDurability < maxDurability * 0.5
                                                    ? "medium"
                                                    : "high"
                                                }`}
                                            style={{
                                                width: `${Math.min(100, Math.max(0, (currentDurability / maxDurability) * 100))}%`
                                            }}
                                        />
                                    </div>
                                </div>
                            )}
                        </div>

                        {/* Right: Actions */}
                        <div className="item-actions-section">
                            {item.consumable && (
                                <button className="action-btn use" onClick={() => onUseItem(item.item_id, item.id)}>Use</button>
                            )}
                            {item.equippable && !item.is_equipped && (
                                <button className="action-btn equip" onClick={() => onEquipItem(item.id)}>Equip</button>
                            )}
                            {item.is_equipped && (
                                <button className="action-btn unequip" onClick={() => onUnequipItem(item.slot)}>Unequip</button>
                            )}

                            <div className="drop-actions-group">
                                {item.quantity > 1 && (
                                    <button className="action-btn drop" onClick={() => onDropItem(item.item_id, item.id, 1)}>x1</button>
                                )}
                                {item.quantity >= 5 && (
                                    <button className="action-btn drop" onClick={() => onDropItem(item.item_id, item.id, 5)}>x5</button>
                                )}
                                {item.quantity >= 10 && (
                                    <button className="action-btn drop" onClick={() => onDropItem(item.item_id, item.id, 10)}>x10</button>
                                )}
                                <button className={`action-btn drop ${item.quantity === 1 ? 'single' : ''}`} onClick={() => onDropItem(item.item_id, item.id, item.quantity === 1 ? 1 : item.quantity)}>
                                    {item.quantity === 1 ? 'Drop' : 'All'}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }

    return (
        <div className="workbench-overlay" onClick={(e: MouseEvent<HTMLDivElement>) => {
            if (e.target === e.currentTarget) onClose()
        }}>
            <div className="workbench-menu inventory-modal-redesign">
                {/* Top Bar: Capacity & Backpack Info */}
                <div className="inventory-top-bar">
                    <div className="inventory-capacity-summary">
                        <div className="capacity-metric">
                            <span className="metric-icon">⚖️</span>
                            <div className="metric-bar-container">
                                <div className="metric-text">
                                    Weight: {(profile.current_weight || 0).toFixed(1)} / {profile.max_weight || 0} kg
                                </div>
                                <div className="metric-bar">
                                    <div
                                        className="metric-fill weight"
                                        style={{ width: `${Math.min(100, ((profile.current_weight || 0) / (profile.max_weight || 1)) * 100)}%` }}
                                    ></div>
                                </div>
                            </div>
                        </div>

                        <div className="capacity-metric">
                            <span className="metric-icon">📦</span>
                            <div className="metric-bar-container">
                                <div className="metric-text">
                                    Volume: {(profile.current_volume || 0).toFixed(1)} / {profile.max_volume || 0} L
                                </div>
                                <div className="metric-bar">
                                    <div
                                        className="metric-fill volume"
                                        style={{ width: `${Math.min(100, ((profile.current_volume || 0) / (profile.max_volume || 1)) * 100)}%` }}
                                    ></div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div className="inventory-backpack-info">
                        {equipment?.backpack ? (
                            <div className="backpack-status active">
                                <span className="backpack-icon">🎒</span>
                                <span className="backpack-name">{equipment.backpack.name}</span>
                                <span className="backpack-stats">
                                    (+{equipment.backpack.unique_stats?.weight_capacity || equipment.backpack.stats?.weight_capacity || 0}kg /
                                    +{equipment.backpack.unique_stats?.volume_capacity || equipment.backpack.stats?.volume_capacity || 0}L)
                                </span>
                            </div>
                        ) : (
                            <div className="backpack-status inactive">
                                <span className="backpack-icon">🚫</span>
                                <span>No Backpack Equipped</span>
                            </div>
                        )}
                        <button className="close-btn" onClick={onClose}>✕</button>
                    </div>
                </div>

                <div className="inventory-main-layout">
                    {/* Left Sidebar: Categories */}
                    <div className="inventory-sidebar-filters">
                        {categories.map(cat => (
                            <button
                                key={cat.id}
                                className={`category-btn ${inventoryCategoryFilter === cat.id ? 'active' : ''}`}
                                onClick={() => onSetInventoryCategoryFilter(cat.id)}
                            >
                                <span className="cat-icon">{cat.icon}</span>
                                <span className="cat-label">{cat.label}</span>
                            </button>
                        ))}
                    </div>

                    {/* Right Content: Search & List */}
                    <div className="inventory-content-area">
                        <div className="inventory-search-bar">
                            <span className="search-icon">🔍</span>
                            <input
                                type="text"
                                placeholder="Search items..."
                                value={inventoryFilter}
                                onChange={(e: ChangeEvent<HTMLInputElement>) => onSetInventoryFilter(e.target.value)}
                            />
                        </div>

                        <div className="inventory-items-grid">
                            {filteredItems.length === 0 ? (
                                <div className="empty-state">
                                    <span className="empty-icon">📦</span>
                                    <p>No items found in this category</p>
                                </div>
                            ) : (
                                inventoryCategoryFilter === 'all' ? (
                                    <>
                                        {/* Equipped */}
                                        {filteredItems.some((i: any) => i.is_equipped) && (
                                            <>
                                                <div className="category-header">⚔️ Equipped</div>
                                                {filteredItems.filter((i: any) => i.is_equipped).map((item: any, i: number) => renderItemCard(item, i))}
                                            </>
                                        )}

                                        {/* Categories */}
                                        {categories.filter(c => c.id !== 'all').map(cat => {
                                            const categoryItems = filteredItems.filter((i: any) => !i.is_equipped && i.type === cat.id);
                                            if (categoryItems.length === 0) return null;
                                            return (
                                                <div key={cat.id}>
                                                    <div className="category-header">{cat.icon} {cat.label}</div>
                                                    {categoryItems.map((item: any, i: number) => renderItemCard(item, i))}
                                                </div>
                                            );
                                        })}
                                    </>
                                ) : (
                                    filteredItems.map((item: any, i: number) => renderItemCard(item, i))
                                )
                            )}
                        </div>
                    </div>
                </div>
            </div >
        </div >
    )
}

export default InventoryModal
