import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import type { PlayerState, Profile, Equipment } from './types'
import { getAssetPath } from '../../utils/assetPath'
import { getTranslatedText } from '../../utils/i18nUtils'
import InventoryModal from './InventoryModal'
import { GameProgressBar } from '../common/GameProgressBar'
import { GameTooltip } from '../common/GameTooltip'
import { GameButton } from '../common/GameButton'
import { useAudio } from '../../contexts/AudioContext'

interface PlayerSidebarProps {
  playerState: PlayerState
  profile: Profile | null
  equipment: Equipment
  inventoryFilter: string
  inventoryCategoryFilter: string
  mobileMenuOpen: string
  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
  onSpendPoint: (stat: string) => void
}

function PlayerSidebar({
  playerState,
  profile,
  equipment,
  inventoryFilter,
  inventoryCategoryFilter,
  mobileMenuOpen,
  onSetInventoryFilter,
  onSetInventoryCategoryFilter,
  onUseItem,
  onEquipItem,
  onUnequipItem,
  onDropItem,
  onSpendPoint
}: PlayerSidebarProps) {
  const [showInventory, setShowInventory] = useState(false)
  const { t } = useTranslation()
  const { playSfx } = useAudio()

  const renderEquipmentSlot = (slot: string, item: any, label: string) => {
    // Construct the tooltip content if item exists
    const tooltipContent = item ? (
      <div className="game-tooltip-stats">
        <div className="item-tooltip-name" style={{ color: 'var(--game-text-highlight)', fontWeight: 'bold' }}>
          {getTranslatedText(item.name)}
        </div>
        {item.tier !== undefined && item.tier !== null && item.tier > 0 && (
          <div className="item-tooltip-stat" style={{ color: '#fbbf24' }}>
            ⭐ Tier: {item.tier}
          </div>
        )}
        {item.description && <div className="item-tooltip-desc" style={{ color: 'var(--game-text-secondary)', fontStyle: 'italic', marginBottom: '0.5rem' }}>{getTranslatedText(item.description)}</div>}
        {(item.unique_stats || item.stats) && Object.keys(item.unique_stats || item.stats).length > 0 && (
          <div style={{ display: 'grid', gridTemplateColumns: 'auto auto', gap: '0.25rem 1rem' }}>
            {(item.unique_stats?.armor || item.stats?.armor) && (
              <div className="item-tooltip-stat">
                {t('stats.armor')}: <span style={{ color: 'var(--game-color-success)' }}>+{item.unique_stats?.armor || item.stats?.armor}</span>
              </div>
            )}
            {(item.unique_stats?.hp_max || item.stats?.hp_max) && (
              <div className="item-tooltip-stat">
                {t('stats.hp')}: <span style={{ color: 'var(--game-color-success)' }}>+{item.unique_stats?.hp_max || item.stats?.hp_max}</span>
              </div>
            )}
            {(item.unique_stats?.stamina_max || item.stats?.stamina_max) && (
              <div className="item-tooltip-stat">
                {t('stats.stamina')}: <span style={{ color: 'var(--game-color-stamina)' }}>+{item.unique_stats?.stamina_max || item.stats?.stamina_max}</span>
              </div>
            )}
            {(item.unique_stats?.damage_min !== undefined || item.stats?.damage_min !== undefined) &&
              (item.unique_stats?.damage_max !== undefined || item.stats?.damage_max !== undefined) && (
                <div className="item-tooltip-stat">
                  {t('stats.damage')}: <span style={{ color: 'var(--game-color-primary)' }}>{item.unique_stats?.damage_min || item.stats?.damage_min}-{item.unique_stats?.damage_max || item.stats?.damage_max}</span>
                </div>
              )}
            {(item.unique_stats?.weight_capacity || item.stats?.weight_capacity) && (
              <div className="item-tooltip-stat">
                {t('stats.weight')}: +{item.unique_stats?.weight_capacity || item.stats?.weight_capacity}kg
              </div>
            )}
            {(item.unique_stats?.volume_capacity || item.stats?.volume_capacity) && (
              <div className="item-tooltip-stat">
                {t('stats.volume')}: +{item.unique_stats?.volume_capacity || item.stats?.volume_capacity}L
              </div>
            )}
          </div>
        )}
        {item.durability !== undefined && item.durability !== null && (
          <div className="item-tooltip-stat" style={{ marginTop: '0.5rem' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
              <span>{t('stats.durability')}:</span>
              <span>{item.durability}/{item.max_durability}</span>
            </div>
            <GameProgressBar
              value={item.durability}
              max={item.max_durability}
              type="durability"
              height="6px"
              showText={false}
            />
          </div>
        )}
      </div>
    ) : label; // Show label if no item

    return (
      <div className={`equipment-slot game-slot ${item ? 'filled' : 'empty'}`}>
        {item ? (
          <>
            <GameTooltip content={t('game.unequip')}>
              <button className="equipment-unequip-btn game-btn game-btn-icon" onClick={(e) => { e.stopPropagation(); onUnequipItem(slot); playSfx('/audio/sfx/unequip.wav'); }}>✕</button>
            </GameTooltip>
            <GameTooltip content={tooltipContent}>
              <div className="equipment-item-content">
                {item.image_path ? (
                  <img
                    src={getAssetPath(item.image_path)}
                    alt={getTranslatedText(item.name)}
                    className="equipment-emoji"
                    style={{ width: '100%', height: '100%', objectFit: 'contain' }}
                  />
                ) : (
                  <span className="equipment-emoji" style={{ fontSize: '2rem' }}>{item.emoji}</span>
                )}
                {item.durability !== undefined && item.durability !== null && (
                  <div className="equipment-durability-bar-container" style={{ width: '90%', marginTop: 'auto', marginBottom: '4px' }}>
                    <GameProgressBar
                      value={item.durability}
                      max={item.max_durability}
                      type="durability"
                      height="4px"
                      showText={false}
                    />
                  </div>
                )}
              </div>
            </GameTooltip>
          </>
        ) : (
          <GameTooltip content={label}>
            <img
              src={getAssetPath(`/images/placeholder/${slot}_placeholder.webp`)}
              alt={label}
              className="equipment-placeholder-img"
              style={{ width: '100%', height: '100%', objectFit: 'contain', opacity: 0.5 }}
            />
          </GameTooltip>
        )}
      </div>
    )
  }

  return (
    <div className={`right-sidebar mobile-menu-panel ${mobileMenuOpen === 'right' ? 'open' : ''}`}>
      {/* Profile Stats */}
      <div className="profile-sidebar">
        <h3 className="sidebar-title">
          {profile?.name || 'Character'} <span className="title-level">(Lv. {profile?.level || 1})</span>
        </h3>

        <div className="sidebar-stat-bars">
          <div className="sidebar-stat-bar">
            <GameProgressBar
              value={playerState.health}
              max={playerState.max_health}
              type="health"
              showText={true}
              height="10px"
              label={
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                  {t('stats.hp')}
                  <div className="status-indicators" style={{ display: 'flex', gap: '5px' }}>
                    {playerState.status_effects?.filter((e: any) => e.damage_per_tick !== 0).map((e: any) => (
                      <span key={e.id} className={`stat-indicator ${e.damage_per_tick > 0 ? 'negative' : 'positive'}`} style={{
                        color: e.damage_per_tick > 0 ? '#ff6b6b' : '#4caf50',
                        fontSize: '0.85rem',
                        fontWeight: 'bold'
                      }}>
                        {e.damage_per_tick > 0 ? `-${e.damage_per_tick}` : `+${Math.abs(e.damage_per_tick)}`}/t ({e.ticks_remaining})
                      </span>
                    ))}
                  </div>
                </div>
              }
            />
          </div>

          <div className="sidebar-stat-bar">
            <GameProgressBar
              value={playerState.stamina}
              max={playerState.max_stamina}
              type="stamina"
              showText={true}
              height="10px"
              label={t('stats.stamina')}
            />
          </div>

          <div className="sidebar-stat-bar">
            <GameProgressBar
              value={profile?.xp || 0}
              max={(profile?.level || 1) * 100}
              type="xp"
              showText={true}
              height="10px"
              label={t('stats.xp')}
            />
            <div className="xp-text-detail" style={{ fontSize: '0.7rem', color: '#718096', textAlign: 'right', marginTop: '2px' }}>
              {Math.floor(((profile?.level || 1) * 100) - (profile?.xp || 0))} XP to next level
            </div>
          </div>
        </div>

        {profile && (
          <div className="sidebar-stats">
            {profile.unspent_points > 0 && (
              <div className="sidebar-stat-row highlight">
                <span className="sidebar-label">{t('stats.unspentPoints')}:</span>
                <span className="sidebar-value">{profile.unspent_points}</span>
              </div>
            )}

            <div className="sidebar-divider"></div>

            {/* Compact 2x2 Stats Grid */}
            <div className="stats-grid">
              <div className="sidebar-stat-row compact">
                <span className="sidebar-label">{t('stats.strength')}:</span>
                <span className="sidebar-value">{profile.strength}</span>
                {profile.unspent_points > 0 && (
                  <button className="stat-plus-btn" onClick={() => onSpendPoint('strength')}>+</button>
                )}
              </div>
              <div className="sidebar-stat-row compact">
                <span className="sidebar-label">{t('stats.agility')}:</span>
                <span className="sidebar-value">{profile.agility}</span>
                {profile.unspent_points > 0 && (
                  <button className="stat-plus-btn" onClick={() => onSpendPoint('agility')}>+</button>
                )}
              </div>
              <div className="sidebar-stat-row compact">
                <span className="sidebar-label">{t('stats.endurance')}:</span>
                <span className="sidebar-value">{profile.endurance}</span>
                {profile.unspent_points > 0 && (
                  <button className="stat-plus-btn" onClick={() => onSpendPoint('endurance')}>+</button>
                )}
              </div>
              <div className="sidebar-stat-row compact">
                <span className="sidebar-label">{t('stats.intellect')}:</span>
                <span className="sidebar-value">{profile.intellect}</span>
                {profile.unspent_points > 0 && (
                  <button className="stat-plus-btn" onClick={() => onSpendPoint('intellect')}>+</button>
                )}
              </div>
            </div>

            <div className="sidebar-divider"></div>

            {/* Inventory Capacity - matching HP/Stamina/XP style */}
            <div className="sidebar-stat-bar">
              <GameProgressBar
                value={profile.current_weight || 0}
                max={profile.max_weight || 0}
                type="weight"
                showText={true}
                label={t('stats.weight')}
                unit="kg"
                height="10px"
              />
            </div>

            <div className="sidebar-stat-bar">
              <GameProgressBar
                value={profile.current_volume || 0}
                max={profile.max_volume || 0}
                type="volume"
                showText={true}
                label={t('stats.volume')}
                unit="L"
                height="10px"
              />
            </div>
          </div>
        )}

        <GameButton
          className="open-inventory-btn"
          variant="primary"
          size="lg"
          onClick={() => setShowInventory(true)}
          style={{ width: '100%', justifyContent: 'center' }}
        >
          {t('game.inventory')}
        </GameButton>
      </div>

      <div className="equipment-sidebar">
        <h3>{t('game.equipment')}</h3>
        <div className="equipment-grid">
          {/* Row 1: Head */}
          <div className="equipment-row">
            {renderEquipmentSlot('head', equipment.head, t('equipment.head'))}
          </div>

          {/* Row 2: Weapon, Torso, Backpack */}
          <div className="equipment-row three-cols">
            {renderEquipmentSlot('weapon', equipment.weapon, t('equipment.weapon'))}
            {renderEquipmentSlot('torso', equipment.torso, t('equipment.torso'))}
            {renderEquipmentSlot('backpack', equipment.backpack, t('equipment.backpack'))}
          </div>

          {/* Row 3: Legs & Feet */}
          <div className="equipment-row two-cols">
            {renderEquipmentSlot('legs', equipment.legs, t('equipment.legs'))}
            {renderEquipmentSlot('feet', equipment.feet, t('equipment.feet'))}
          </div>
        </div>
      </div>

      {showInventory && profile && (
        <InventoryModal
          playerState={playerState}
          profile={profile}
          equipment={equipment}
          inventoryFilter={inventoryFilter}
          inventoryCategoryFilter={inventoryCategoryFilter}
          onClose={() => setShowInventory(false)}
          onSetInventoryFilter={onSetInventoryFilter}
          onSetInventoryCategoryFilter={onSetInventoryCategoryFilter}
          onUseItem={onUseItem}
          onEquipItem={onEquipItem}
          onUnequipItem={onUnequipItem}
          onDropItem={onDropItem}
        />
      )}
    </div>
  )
}

export default PlayerSidebar
