import React, { useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useAudio } from '../../contexts/AudioContext';
import { CombatState, AnimationState, FloatingText } from './CombatTypes';
import { Equipment } from './types';
import './CombatEffects.css';
import { GameProgressBar } from '../common/GameProgressBar';

interface CombatViewProps {
  state: CombatState;
  animState: AnimationState;
  floatingTexts: FloatingText[];
  onAction: (action: string, itemId?: string) => void;
  onClose: () => void;
  onShowSupplies: () => void;
  isProcessing: boolean;
  combatResult: 'victory' | 'defeat' | 'fled' | null;
  equipment?: Equipment | any;
  playerName?: string;
}

export const CombatView: React.FC<CombatViewProps> = ({
  state,
  animState,
  floatingTexts,
  onAction,
  onClose,
  onShowSupplies,
  isProcessing,
  combatResult,
  equipment,
  playerName
}) => {
  const { t } = useTranslation();
  const { playSfx } = useAudio();

  // SFX Logic triggered by state or anim states
  useEffect(() => {
    // Check for combat completion sounds
    if (combatResult === 'victory') {
      playSfx('/audio/sfx/victory.wav');
    } else if (combatResult === 'defeat') {
      playSfx('/audio/sfx/defeat.wav');
    } else if (combatResult === 'fled') {
      playSfx('/audio/sfx/flee.wav');
    }
  }, [combatResult, playSfx]);

  // Track animation states to trigger attack/hit sounds
  useEffect(() => {
    // Player Attack Sound
    if (animState.playerAttacking) {
      if (equipment && equipment.main_hand) {
        // Try to derive weapon type from name or properties
        // This is a naive check; ideally the backend sends weapon type.
        // We'll check for common keywords in the icon or name.
        let weaponType = 'default';
        const weaponName = (typeof equipment.main_hand.name === 'string'
          ? equipment.main_hand.name
          : (equipment.main_hand.name?.en || '')
        ).toLowerCase();

        if (weaponName.includes('sword') || weaponName.includes('blade')) weaponType = 'sword';
        else if (weaponName.includes('axe')) weaponType = 'axe';
        else if (weaponName.includes('bow')) weaponType = 'bow';
        else if (weaponName.includes('hammer') || weaponName.includes('mace')) weaponType = 'blunt';
        else if (weaponName.includes('dagger')) weaponType = 'dagger';
        else if (weaponName.includes('fist') || !equipment.main_hand) weaponType = 'punch';

        playSfx(`/audio/sfx/attack_${weaponType}.wav`, '/audio/sfx/attack_default.wav');
      } else {
        // Unarmed
        playSfx('/audio/sfx/attack_punch.wav', '/audio/sfx/attack_default.wav');
      }
    }

    // Enemy Attack Sound
    if (animState.enemyAttacking) {
      // We can use state.npcId to get specific enemy sounds (only for PvE)
      if (state.npcId && !state.isPvP) {
        playSfx(`/audio/sfx/attack_enemy_${state.npcId}.wav`, '/audio/sfx/attack_enemy_default.wav');
      } else {
        playSfx('/audio/sfx/attack_enemy_default.wav', '/audio/sfx/attack_default.wav');
      }
    }

    // Hit reaction (when shaking) - distinguishing origin would be better 
    // but animState.shaking is general. 
    // However, we know who is attacking from the other flags, so the *other* valid one is getting hit.
    // Simpler: just play a generic hit sound when someone gets hit.
    if (animState.shaking && !animState.playerAttacking && !animState.enemyAttacking) {
      // This case might not happen often if shaking is coupled with attacking in parent.
      // Actually Combat.tsx triggers 'shaking' ON attack for impact effect.
      // So we might play 'hit' sound alongside attack sound?
      // Or let's trigger hit sound specifically when damage numbers appear.
      // Since we can't easily hook into floating text creation here without prop drill or context,
      // we'll rely on the visual 'flashing' which usually implies taking damage.
    }

    if (animState.flashing) {
      // Someone took damage
      playSfx('/audio/sfx/hit.wav');
    }

  }, [animState.playerAttacking, animState.enemyAttacking, animState.flashing, equipment, state.npcId, playSfx]);

  // Auto-scroll log is less critical for table but good to keep if we can target the container
  // For the table, we might just rely on normal scroll or add ref to the container
  // Auto-scroll log to top on new entry
  useEffect(() => {
    const container = document.querySelector('.combat-log-container');
    if (container) {
      container.scrollTop = 0;
    }
  }, [state.messages]);

  return (
    <div className="combat-container">

      {/* Header (Location View Style) */}
      <div className="combat-header">
        <h2 className="centered-heading">
          {state.isPvP ? t('combat.pvp_title') : t('combat.title')}
          <span style={{ margin: '0 0.5rem', color: '#aaa', fontSize: '0.9em' }}>vs</span>
          {state.npcName || t('combat.unknown_enemy')}

          {state.turnTimeRemaining !== undefined && (
            <span className="danger-badge danger-2" style={{ fontSize: '0.8rem', marginLeft: '0.5rem' }}>
              ⏳ {state.turnTimeRemaining} s
            </span>
          )}
          {state.isPvP && (
            <span
              className={`danger-badge ${state.yourTurn ? 'danger-1' : 'danger-3'}`}
              style={{ fontSize: '0.8rem', marginLeft: '0.5rem', fontWeight: 'bold' }}
            >
              {state.yourTurn ? '🎯 ' + t('combat.your_turn') : '⏳ ' + t('combat.opponent_turn')}
            </span>
          )}
        </h2>
      </div>

      {/* Main Content Vertical Stack */}
      <div className="combat-main-content">

        {/* 1. Enemy Avatar (Location Image Style) */}
        {/* Shake on npcHit, Attack on enemyAttacking, Dead on victory */}
        <div className={`enemy-display ${animState.enemyAttacking ? 'attacking' : ''} ${animState.npcHit ? 'shake-effect flash-hit' : ''} ${combatResult === 'victory' ? 'dead' : ''}`}>
          <div className="location-image-container">
            {state.npcImage ? (
              <img src={state.npcImage} alt={state.npcName} className="location-image" />
            ) : (
              <div className="enemy-placeholder">💀</div>
            )}
          </div>
        </div>

        {/* 2. HP Bars (Character Sheet Style) - Staggered Lines */}
        <div className="combat-stats-container" style={{ position: 'relative' }}>

          {/* Floating Text - Enemy (Left 60%) */}
          <div style={{
            position: 'absolute',
            top: '20px',
            left: 0,
            width: '60%',
            display: 'flex',
            justifyContent: 'center',
            pointerEvents: 'none',
            zIndex: 2000
          }}>
            {floatingTexts.filter(ft => ft.origin === 'enemy').map(ft => (
              <div key={ft.id} className={`floating-text type-${ft.type}`} style={{ position: 'absolute' }}>
                {ft.text}
              </div>
            ))}
          </div>

          {/* Floating Text - Player (Right 60%) */}
          <div style={{
            position: 'absolute',
            bottom: '20px',
            right: 0,
            width: '60%',
            display: 'flex',
            justifyContent: 'center',
            pointerEvents: 'none',
            zIndex: 2000
          }}>
            {floatingTexts.filter(ft => ft.origin === 'player').map(ft => (
              <div key={ft.id} className={`floating-text type-${ft.type}`} style={{ position: 'absolute' }}>
                {ft.text}
              </div>
            ))}
          </div>

          {/* Enemy HP (Left) */}
          <div className={`stat-block enemy ${animState.npcHit ? 'shake-effect' : ''}`}>
            <GameProgressBar
              label={state.npcName || t('common.enemy')}
              value={state.npcHp}
              max={state.npcMaxHp}
              type="enemy_health"
              showText={true}
              height="10px"
              labelAlignment="right"
            />
          </div>

          {/* Player HP (Right) */}
          <div className={`stat-block player ${animState.playerHit ? 'shake-effect flash-hit' : ''}`}>
            <GameProgressBar
              label={playerName || t('common.you')}
              value={state.playerHp}
              max={state.playerMaxHp}
              type="health"
              showText={true}
              height="10px"
              align="right"
              labelAlignment="left"
            />
          </div>
        </div>

        {/* 3. Actions */}
        <div className="combat-actions">
          <button
            className="btn btn-primary full-width glow-effect"
            onClick={onClose}
            style={{ display: combatResult ? 'block' : 'none', margin: '0 auto' }}
          >
            {t('common.close')}
          </button>

          <div className="combat-actions-group" style={{ display: !combatResult ? 'grid' : 'none', gridTemplateColumns: '1fr 1fr', gap: '0.75rem', width: '100%', maxWidth: '400px', margin: '0 auto' }}>
            <button
              className="btn btn-attack"
              onClick={() => onAction('attack')}
              disabled={isProcessing || !state.yourTurn}
            >
              👊 {t('combat.actions.attack')}
            </button>

            <button
              className="btn btn-defend"
              onClick={() => onAction('defend')}
              disabled={isProcessing || !state.yourTurn}
            >
              🛡️ {t('combat.actions.defend')}
            </button>

            <button
              className="btn btn-supplies"
              onClick={onShowSupplies}
              disabled={isProcessing || !state.yourTurn}
            >
              🎒 {t('combat.actions.supplies')}
            </button>

            <button
              className="btn btn-flee"
              onClick={() => onAction('flee')}
              disabled={isProcessing || !state.yourTurn}
            >
              🏃 {t('combat.actions.flee')}
            </button>
          </div>
        </div>

        {/* 4. Log (Table) */}
        <div className="combat-log-container">
          <table className="combat-log-table">
            <tbody>
              {[...state.messages].reverse().map((msg, index) => {
                let text = "";
                let className = `log-row log-${msg.type}`;

                if (msg.data && msg.data.message) {
                  text = msg.data.message;
                } else {
                  switch (msg.type) {
                    case 'combat_start': text = t('combat.start'); break;
                    case 'combat_timeout': text = t('combat.turn_timeout'); className += " text-warning"; break;
                    case 'player_attack':
                      if (msg.origin === 'enemy') {
                        text = t('combat.log.enemy_attack', { damage: msg.data?.damage || 0 });
                        className += " text-danger";
                      } else {
                        text = t('combat.log.player_attack', { damage: msg.data?.damage || 0 });
                      }
                      break;
                    case 'enemy_attack':
                      text = t('combat.log.enemy_attack', { damage: msg.data?.damage || 0 });
                      className += " text-danger";
                      break;
                    case 'player_miss': text = t('combat.log.player_miss'); break;
                    case 'enemy_miss': text = t('combat.log.enemy_miss'); break;
                    case 'victory': text = t('combat.victory'); className += " text-success bold"; break;
                    case 'player_defeated': text = t('combat.defeat'); className += " text-danger bold"; break;
                    case 'flee_success': text = t('combat.flee.success'); break;
                    case 'flee_fail': text = t('combat.flee.fail'); break;
                    case 'item_broken': text = t('combat.item_broken', { item: msg.data?.item_name }); break;
                    case 'xp_gain': text = t('combat.log.xp_gain', { xp: msg.data?.xp }); className += " text-warning"; break;
                    case 'damage':
                      if (msg.origin === 'enemy') {
                        text = t('combat.log.enemy_attack', { damage: msg.data?.damage || 0 });
                        className += " text-danger";
                      } else {
                        text = t('combat.log.player_attack', { damage: msg.data?.damage || 0 });
                      }
                      break;
                    case 'text': text = msg.data?.text || ""; break;
                    case 'item_used':
                      text = t('combat.log.item_used', { item: msg.data?.item_name || '' });
                      if (msg.data?.effects) text += msg.data.effects; // Append effects string if backend still sends it
                      className += " text-info";
                      break;
                    case 'effect_applied':
                      text = t('combat.log.effect_applied', {
                        effect: msg.data?.effect_name,
                        target: msg.data?.target === 'enemy' ? t('common.enemy') : t('common.you')
                      });
                      className += " text-warning";
                      break;
                    default: text = msg.type;
                  }
                }
                const time = msg.timestamp || new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });

                return (
                  <tr key={index} className={className}>
                    <td className="log-time">[{time}]</td>
                    <td className="log-event">{text}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

      </div>

      {/* Overlay for Enemy Turn / Processing */}
      {
        isProcessing && !combatResult && state.turn === 'enemy' && (
          <div className="turn-overlay">
            {t('combat.enemy_turn')}
          </div>
        )
      }
    </div >
  );
};
