import { useState } from 'react'
import { useGame } from '../../contexts/GameContext'
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 { GameItemCard } from '../common/GameItemCard'
import { GameDropdown } from '../common/GameDropdown'
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
  onOpenQuestJournal: () => void
  onOpenCharacterSheet: () => void
}

function PlayerSidebar({
  playerState,
  profile,
  equipment,
  inventoryFilter,
  inventoryCategoryFilter,
  mobileMenuOpen,
  onSetInventoryFilter,
  onSetInventoryCategoryFilter,
  onUseItem,
  onEquipItem,
  onUnequipItem,
  onDropItem,
  onSpendPoint,
  onOpenQuestJournal,
  onOpenCharacterSheet
}: PlayerSidebarProps) {
  const [showInventory, setShowInventory] = useState(false)
  const [activeSlot, setActiveSlot] = useState<string | null>(null)
  const { t } = useTranslation()
  const { playSfx } = useAudio()
  const { state } = useGame() // Use global state to check quests

  // Check if any quest is ready to turn in
  const hasReadyQuests = state.quests.active?.some((q: any) => {
    // Check if all objectives met
    if (!q.objectives) return false;
    return q.objectives.every((obj: any) => {
      const current = q.progress?.[obj.target] || 0;
      return current >= obj.count;
    });
  });

  const renderEquipmentSlot = (slot: string, item: any, label: string) => {
    // Merge with full inventory data to ensure tooltips have weight/volume
    const fullItemInfo = playerState.inventory?.find((i: any) => i.is_equipped && i.equipment_slot === slot) || item;

    return (
      <div className={`equipment-slot game-slot ${item ? 'filled' : 'empty'}`}>
        {item ? (
          <>
            <GameItemCard
              item={fullItemInfo}
              showTooltip={activeSlot !== slot} // Hide tooltip when dropdown configures
              showDurability={true}
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                // Toggle active slot
                setActiveSlot(activeSlot === slot ? null : slot);
              }}
              isActive={activeSlot === slot}
              className="equipment-item-content"
              style={{ width: '100%', height: '100%' }}
            />
            {activeSlot === slot && (
              <GameDropdown isOpen={true} onClose={() => setActiveSlot(null)} width="160px">
                <div className="game-dropdown-header">
                  {getTranslatedText(item.name)}
                </div>
                <GameButton
                  variant="info"
                  size="sm"
                  onClick={(e) => {
                    e.stopPropagation();
                    setActiveSlot(null);
                    onUnequipItem(slot);
                    playSfx('/audio/sfx/unequip.wav');
                  }}
                  style={{ width: '100%', justifyContent: 'flex-start' }}
                >
                  {t('game.unequip')}
                </GameButton>
              </GameDropdown>
            )}
          </>
        ) : (
          <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>
            )}



            {/* 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>



            {/* Inventory Capacity - Weight & Volume side-by-side */}
            <div className="sidebar-capacity-row">
              <div className="sidebar-stat-bar" style={{ flex: 1 }}>
                <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" style={{ flex: 1 }}>
                <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>
          </div>
        )}

        <div className="sidebar-buttons" style={{ display: 'flex', gap: '0.5rem', marginTop: '0.5rem' }}>
          <GameButton
            className="open-inventory-btn"
            variant="primary"
            size="sm"
            onClick={() => setShowInventory(true)}
            style={{ flex: 1, justifyContent: 'center' }}
          >
            {t('game.inventory')}
          </GameButton>

          <GameButton
            className="quest-journal-btn"
            variant="info"
            size="sm"
            onClick={onOpenCharacterSheet}
            style={{ flex: 1, justifyContent: 'center' }}
          >
            <span>📊</span> {t('common.characterSheet', 'Stats')}
          </GameButton>

          <GameButton
            className={`quest-journal-btn ${hasReadyQuests ? 'pulse-gold' : ''}`}
            variant={hasReadyQuests ? 'warning' : 'secondary'}
            size="sm"
            onClick={onOpenQuestJournal}
            style={{ flex: 1, justifyContent: 'center' }}
          >
            <span>{hasReadyQuests ? '❗' : '📜'}</span> {t('common.quests')}
          </GameButton>
        </div>
      </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
