import { MouseEvent, ChangeEvent, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useAudio } from '../../contexts/AudioContext'
import { PlayerState, Profile, Equipment } from './types'
import { getAssetPath } from '../../utils/assetPath'
import { getTranslatedText } from '../../utils/i18nUtils'
import './InventoryModal.css'
import { GameTooltip } from '../common/GameTooltip'
import { GameDropdown } from '../common/GameDropdown'
import { GameButton } from '../common/GameButton'
import { GameModal } from './GameModal'
import { ItemStatBadges } from '../common/ItemStatBadges'
import { GameProgressBar } from '../common/GameProgressBar'
import { GameItemCard } from '../common/GameItemCard'
import '../common/GameDropdown.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) {
    const { t } = useTranslation()
    const { playSfx } = useAudio()

    // View Mode State
    const [viewMode, setViewMode] = useState<'list' | 'grid'>(() => {
        return (localStorage.getItem('inventoryViewMode') as 'list' | 'grid') || 'list';
    });

    // Dropdown State
    const [activeDropdown, setActiveDropdown] = useState<number | null>(null); // Uses item.id (inventory ID)
    const [dropdownPos, setDropdownPos] = useState({ x: 0, y: 0 });

    // Play sound on mount
    useEffect(() => {
        playSfx('/audio/sfx/inventory_open.wav')

        // Return cleanup/close sound? usage of "onClose" typically handles it.
        // We can't easily do it on unmount if the parent unmounts it instantly.
        // But for "close" button click we can play it.
    }, [])

    const toggleViewMode = () => {
        const newMode = viewMode === 'list' ? 'grid' : 'list';
        setViewMode(newMode);
        localStorage.setItem('inventoryViewMode', newMode);
        playSfx('/audio/sfx/click.wav'); // Or a generic interaction sound
    };

    const handleItemClick = (e: MouseEvent, item: any) => {
        if (viewMode === 'grid') {
            e.stopPropagation();
            // Toggle dropdown
            if (activeDropdown === item.id) {
                setActiveDropdown(null);
            } else {
                setDropdownPos({ x: e.clientX, y: e.clientY });
                setActiveDropdown(item.id);
            }
        }
    };

    const handleClose = () => {
        playSfx('/audio/sfx/inventory_close.wav')
        onClose()
    }

    // ... existing categories ...
    const categories = [
        { id: 'all', label: t('categories.all'), icon: '🎒' },
        { id: 'weapon', label: t('categories.weapon'), icon: '⚔️' },
        { id: 'armor', label: t('categories.armor'), icon: '🛡️' },
        { id: 'clothing', label: t('categories.clothing'), icon: '👕' },
        { id: 'backpack', label: t('categories.backpack'), icon: '🎒' },
        { id: 'tool', label: t('categories.tool'), icon: '🛠️' },
        { id: 'consumable', label: t('categories.consumable'), icon: '🍖' },
        { id: 'resource', label: t('categories.resource'), icon: '📦' },
        { id: 'quest', label: t('categories.quest'), icon: '📜' },
        { id: 'misc', label: t('categories.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 = getTranslatedText(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 (getTranslatedText(a.name) || '').localeCompare(getTranslatedText(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={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}` : ''} ${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}`}>{getTranslatedText(item.name)}</h4>
                        {item.is_equipped && <span className="item-card-equipped">{t('game.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">{getTranslatedText(item.description)}</p>}

                            {/* Stats Row - Reusable Badges */}
                            <ItemStatBadges item={item} />

                            {/* Durability Bar */}
                            {hasDurability && (
                                <div style={{ marginTop: '0.5rem' }}>
                                    <div className="durability-header">
                                        <span>{t('game.durability')}</span>
                                        <span className={
                                            currentDurability < maxDurability * 0.2
                                                ? "durability-text-low"
                                                : ""
                                        }>
                                            {currentDurability} / {maxDurability}
                                        </span>
                                    </div>
                                    <GameProgressBar
                                        value={currentDurability}
                                        max={maxDurability}
                                        type="durability"
                                        height="6px"
                                        showText={false}
                                    />
                                </div>
                            )}
                        </div>

                        {/* Right: Actions */}
                        <div className="item-actions-section">
                            {item.consumable && (
                                (() => {
                                    const statusEffect = item.effects?.status_effect;
                                    const isEffectActive = statusEffect && playerState.status_effects.some((e: any) => {
                                        const effectName = typeof e.effect_name === 'string' ? e.effect_name : e.effect_name['en'];
                                        const itemName = typeof statusEffect.name === 'string' ? statusEffect.name : statusEffect.name['en'];
                                        return effectName === itemName;
                                    });

                                    return (
                                        <GameTooltip content={isEffectActive ? t('game.effectAlreadyActive') : ''}>
                                            <button
                                                className={`action-btn use ${isEffectActive ? 'disabled' : ''}`}
                                                disabled={isEffectActive}
                                                onClick={() => {
                                                    if (!isEffectActive) {
                                                        playSfx('/audio/sfx/use.wav')
                                                        onUseItem(item.item_id, item.id)
                                                    }
                                                }}
                                            >
                                                {t('game.use')}
                                            </button>
                                        </GameTooltip>
                                    );
                                })()
                            )}
                            {item.equippable && !item.is_equipped && (
                                <button className="action-btn equip" onClick={() => {
                                    playSfx('/audio/sfx/equip.wav')
                                    onEquipItem(item.id)
                                }}>{t('game.equip')}</button>
                            )}
                            {item.is_equipped && (
                                <button className="action-btn unequip" onClick={() => {
                                    playSfx('/audio/sfx/unequip.wav')
                                    onUnequipItem(item.slot)
                                }}>{t('game.unequip')}</button>
                            )}

                            <div className="drop-actions-group">
                                <button className={`action-btn drop single`} onClick={() => {
                                    playSfx('/audio/sfx/drop.wav')
                                    onDropItem(item.item_id, item.id, 1)
                                }}>
                                    {item.quantity === 1 ? t('game.drop') : 'x1'}
                                </button>
                                {item.quantity >= 5 && (
                                    <button className="action-btn drop" onClick={() => {
                                        playSfx('/audio/sfx/drop.wav')
                                        onDropItem(item.item_id, item.id, 5)
                                    }}>x5</button>
                                )}
                                {item.quantity >= 10 && (
                                    <button className="action-btn drop" onClick={() => {
                                        playSfx('/audio/sfx/drop.wav')
                                        onDropItem(item.item_id, item.id, 10)
                                    }}>x10</button>
                                )}
                                {item.quantity > 1 && (
                                    <button className="action-btn drop" onClick={() => {
                                        playSfx('/audio/sfx/drop.wav')
                                        onDropItem(item.item_id, item.id, item.quantity)
                                    }}>{t('common.all')}</button>
                                )}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }

    const renderGridItem = (item: any, i: number) => {
        // Prepare actions for this item
        const statusEffect = item.effects?.status_effect;
        const isEffectActive = statusEffect && playerState.status_effects.some((e: any) => {
            const effectName = typeof e.effect_name === 'string' ? e.effect_name : e.effect_name['en'];
            const itemName = typeof statusEffect.name === 'string' ? statusEffect.name : statusEffect.name['en'];
            return effectName === itemName;
        });

        return (
            <div key={i} className="inventory-grid-wrapper">
                <GameItemCard
                    item={item}
                    onClick={(e) => handleItemClick(e, item)}
                    isActive={activeDropdown === item.id}
                    showEquipped={true}
                    showQuantity={true}
                />

                {/* Dropdown Menu */}
                {activeDropdown === item.id && (
                    <GameDropdown
                        isOpen={true}
                        onClose={() => setActiveDropdown(null)}
                        position={dropdownPos}
                        width="180px"
                    >
                        <div className="game-dropdown-header">
                            {getTranslatedText(item.name)}
                        </div>

                        {item.consumable && (
                            <GameButton
                                variant="success"
                                size="sm"
                                disabled={isEffectActive}
                                onClick={() => {
                                    if (!isEffectActive) {
                                        playSfx('/audio/sfx/use.wav');
                                        onUseItem(item.item_id, item.id);
                                        setActiveDropdown(null);
                                    }
                                }}
                                style={{ width: '100%', justifyContent: 'flex-start' }}
                            >
                                {t('game.use')}
                            </GameButton>
                        )}

                        {item.equippable && !item.is_equipped && (
                            <GameButton
                                variant="info"
                                size="sm"
                                onClick={() => {
                                    playSfx('/audio/sfx/equip.wav');
                                    onEquipItem(item.id);
                                    setActiveDropdown(null);
                                }}
                                style={{ width: '100%', justifyContent: 'flex-start' }}
                            >
                                {t('game.equip')}
                            </GameButton>
                        )}

                        {item.is_equipped && (
                            <GameButton
                                variant="info"
                                size="sm"
                                onClick={() => {
                                    playSfx('/audio/sfx/unequip.wav');
                                    onUnequipItem(item.slot);
                                    setActiveDropdown(null);
                                }}
                                style={{ width: '100%', justifyContent: 'flex-start' }}
                            >
                                {t('game.unequip')}
                            </GameButton>
                        )}

                        {(item.consumable || (item.equippable && !item.is_equipped) || item.is_equipped) &&
                            <div className="game-dropdown-divider" />
                        }

                        <GameButton
                            variant="danger"
                            size="sm"
                            onClick={(e) => {
                                e.stopPropagation();
                                playSfx('/audio/sfx/drop.wav');
                                onDropItem(item.item_id, item.id, 1);
                                // Keep open
                            }}
                            style={{ width: '100%', justifyContent: 'flex-start' }}
                        >
                            {t('game.drop')} (x1)
                        </GameButton>

                        {item.quantity >= 5 && (
                            <GameButton
                                variant="danger"
                                size="sm"
                                onClick={(e) => {
                                    e.stopPropagation();
                                    playSfx('/audio/sfx/drop.wav');
                                    onDropItem(item.item_id, item.id, 5);
                                    // Keep open
                                }}
                                style={{ width: '100%', justifyContent: 'flex-start' }}
                            >
                                {t('game.drop')} (x5)
                            </GameButton>
                        )}

                        {item.quantity >= 10 && (
                            <GameButton
                                variant="danger"
                                size="sm"
                                onClick={(e) => {
                                    e.stopPropagation();
                                    playSfx('/audio/sfx/drop.wav');
                                    onDropItem(item.item_id, item.id, 10);
                                    // Keep open
                                }}
                                style={{ width: '100%', justifyContent: 'flex-start' }}
                            >
                                {t('game.drop')} (x10)
                            </GameButton>
                        )}

                        {item.quantity > 1 && (
                            <GameButton
                                variant="danger"
                                size="sm"
                                onClick={(e) => {
                                    e.stopPropagation();
                                    playSfx('/audio/sfx/drop.wav');
                                    onDropItem(item.item_id, item.id, item.quantity);
                                    setActiveDropdown(null); // Close on drop all
                                }}
                                style={{ width: '100%', justifyContent: 'flex-start' }}
                            >
                                {t('game.drop')} ({t('common.all')})
                            </GameButton>
                        )}

                    </GameDropdown>
                )}
            </div>
        );
    };

    return (
        <GameModal
            title={t('game.inventory')}
            onClose={handleClose}
            className="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">
                            <span className="metric-text" style={{ marginBottom: '4px', display: 'block' }}>
                                {t('game.weight')}: {(profile.current_weight || 0).toFixed(1)} / {profile.max_weight || 0} kg
                            </span>
                            <GameProgressBar
                                value={profile.current_weight || 0}
                                max={profile.max_weight || 100}
                                type="weight"
                                height="8px"
                                showText={false}
                            />
                        </div>
                    </div>

                    <div className="capacity-metric">
                        <span className="metric-icon">📦</span>
                        <div className="metric-bar-container">
                            <span className="metric-text" style={{ marginBottom: '4px', display: 'block' }}>
                                {t('game.volume')}: {(profile.current_volume || 0).toFixed(1)} / {profile.max_volume || 0} L
                            </span>
                            <GameProgressBar
                                value={profile.current_volume || 0}
                                max={profile.max_volume || 100}
                                type="volume"
                                height="8px"
                                showText={false}
                            />
                        </div>
                    </div>
                </div>

                <div className="inventory-backpack-info">
                    {equipment?.backpack ? (
                        <div className="backpack-status active">
                            <span className="backpack-icon">🎒</span>
                            <span className="backpack-name">{getTranslatedText(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>{t('game.noBackpack')}</span>
                        </div>
                    )}
                    <button className="close-btn" onClick={handleClose}>✕</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="game-search-container" style={{ marginBottom: '1.5rem' }}>
                        <span className="game-search-icon">🔍</span>
                        <input
                            className="game-search-input"
                            type="text"
                            placeholder={t('game.searchItems')}
                            value={inventoryFilter}
                            onChange={(e: ChangeEvent<HTMLInputElement>) => onSetInventoryFilter(e.target.value)}
                        />

                        {/* View Mode Toggle */}
                        <div className="inventory-view-toggle">
                            <button
                                className={`view-toggle-btn ${viewMode === 'list' ? 'active' : ''}`}
                                onClick={toggleViewMode}
                                title={viewMode === 'list' ? "Switch to Grid View" : "Switch to List View"}
                            >
                                {viewMode === 'list' ? '📋' : '🔲'}
                            </button>
                        </div>
                    </div>

                    <div className="inventory-items-grid">
                        {filteredItems.length === 0 ? (
                            <div className="empty-state">
                                <span className="empty-icon">📦</span>
                                <p>{t('game.noItemsFound')}</p>
                            </div>
                        ) : (
                            inventoryCategoryFilter === 'all' ? (
                                <>
                                    {/* Equipped */}
                                    {filteredItems.some((item: any) => item.is_equipped) && (
                                        <>
                                            <div className="category-header">⚔️ {t('game.equipped')}</div>
                                            <div className={`items-container ${viewMode}`}>
                                                {filteredItems.filter((item: any) => item.is_equipped).map((item: any, i: number) =>
                                                    viewMode === 'list' ? renderItemCard(item, i) : renderGridItem(item, i)
                                                )}
                                            </div>
                                        </>
                                    )}

                                    {/* Backpack - grouped by categories */}
                                    {filteredItems.some((item: any) => !item.is_equipped) && (
                                        <>
                                            {/* Group backpack items by category */}
                                            {categories
                                                .filter(cat => cat.id !== 'all') // Exclude 'all' from subcategories
                                                .map(cat => {
                                                    const categoryItems = filteredItems.filter(
                                                        (item: any) => !item.is_equipped && item.type === cat.id
                                                    );
                                                    if (categoryItems.length === 0) return null;
                                                    return (
                                                        <div key={cat.id} className="backpack-category-section">
                                                            <div className="category-header">
                                                                <span className="subcat-icon">{cat.icon}</span>
                                                                <span className="subcat-label">{cat.label}</span>
                                                                <span className="subcat-count">({categoryItems.length})</span>
                                                            </div>
                                                            <div className={`items-container ${viewMode}`}>
                                                                {categoryItems.map((item: any, i: number) =>
                                                                    viewMode === 'list' ? renderItemCard(item, i) : renderGridItem(item, i)
                                                                )}
                                                            </div>
                                                        </div>
                                                    );
                                                })}
                                        </>
                                    )}
                                </>
                            ) : (
                                /* Single category */
                                <div className={`items-container ${viewMode}`}>
                                    {filteredItems.map((item: any, i: number) =>
                                        viewMode === 'list' ? renderItemCard(item, i) : renderGridItem(item, i)
                                    )}
                                </div>
                            )
                        )}
                    </div>
                </div>
            </div>
        </GameModal >
    )
}

export default InventoryModal
