import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { getTranslatedText } from '../../utils/i18nUtils';
import { useAudio } from '../../contexts/AudioContext';
import { CombatState, AnimationState, FloatingText } from './CombatTypes';
import { Equipment } from './types';
import './CombatEffects.css';
import { GameProgressBar } from '../common/GameProgressBar';
import { GameButton } from '../common/GameButton';
import { GameDropdown } from '../common/GameDropdown';
import api from '../../services/api';

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

export const CombatView: React.FC<CombatViewProps> = ({
  state,
  animState,
  floatingTexts,
  onAction,
  onClose,
  onShowSupplies,
  isProcessing,
  playerStamina,
  combatResult,
  equipment,
  playerName,
  locationImage
}) => {
  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">

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

        {/* 1. Combat Scene: Location Background with NPC Overlay */}
        <div className="combat-scene-container">
          {/* Location Background */}
          {locationImage ? (
            <img src={locationImage} alt="Location" className="combat-location-bg" />
          ) : (
            <div className="combat-location-bg combat-location-placeholder">🌄</div>
          )}

          {/* NPC Overlay (bottom-right corner) */}
          <div className={`combat-npc-overlay-container ${animState.npcHit ? 'shake-effect flash-hit' : ''} ${combatResult === 'victory' ? 'dead' : ''}`}>
            {state.npcImage ? (
              <img
                src={state.npcImage}
                alt={state.npcName}
                className={`combat-npc-overlay ${animState.enemyAttacking ? 'attacking' : ''}`}
              />
            ) : (
              <div className="combat-npc-overlay combat-npc-placeholder">💀</div>
            )}
          </div>
        </div>

        {/* PvP Timer & Turn Indicator */}
        {state.isPvP && (
          <div className="combat-pvp-status" style={{
            position: 'absolute',
            top: '60px',
            left: '50%',
            transform: 'translateX(-50%)',
            zIndex: 100,
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            gap: '0.25rem'
          }}>
            {state.turnTimeRemaining !== undefined && (
              <span className="danger-badge danger-2" style={{ fontSize: '1rem', padding: '4px 12px', boxShadow: '0 2px 5px rgba(0,0,0,0.5)' }}>
                ⏳ {state.turnTimeRemaining} s
              </span>
            )}
            <span
              className={`danger-badge ${state.yourTurn ? 'danger-1' : 'danger-3'}`}
              style={{ fontSize: '0.9rem', fontWeight: 'bold' }}
            >
              {state.yourTurn ?
                <span>🎯 {t('combat.yourTurn') || 'Your Turn'}</span> :
                <span>⏳ {t('combat.enemyTurn') || 'Enemy Turn'}</span>
              }
            </span>
          </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={getTranslatedText(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">
          {combatResult && (
            <GameButton
              variant="primary"
              onClick={onClose}
              style={{ width: '100%', maxWidth: '200px', margin: '0 auto' }}
            >
              {t('common.close')}
            </GameButton>
          )}

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

              <AbilitiesDropdown
                onAction={onAction}
                disabled={isProcessing || !state.yourTurn}
                playerStamina={playerStamina}
              />

              <GameButton
                variant="secondary"
                onClick={onShowSupplies}
                disabled={isProcessing || !state.yourTurn}
              >
                🎒 {t('combat.actions.supplies')}
              </GameButton>

              <GameButton
                variant="warning"
                onClick={() => onAction('flee')}
                disabled={isProcessing || !state.yourTurn}
              >
                🏃 {t('combat.actions.flee')}
              </GameButton>
            </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 = getTranslatedText(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: getTranslatedText(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 = getTranslatedText(msg.data?.text) || ""; break;
                    case 'item_used':
                      text = t('combat.log.item_used', { item: getTranslatedText(msg.data?.item_name) || '' });
                      if (msg.data?.effects) text += getTranslatedText(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: getTranslatedText(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"><span>{text}</span></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 >
  );
};


// ─── Abilities Dropdown ───
interface SkillInfo {
  id: string;
  name: any;
  icon: string;
  stamina_cost: number;
  cooldown: number;
  current_cooldown?: number;
}

const AbilitiesDropdown: React.FC<{
  onAction: (action: string) => void;
  disabled: boolean;
  playerStamina?: number;
}> = ({ onAction, disabled, playerStamina }) => {
  const { t } = useTranslation();
  const [open, setOpen] = useState(false);
  const [skills, setSkills] = useState<SkillInfo[]>([]);
  const [loaded, setLoaded] = useState(false);

  const loadSkills = async () => {
    if (open) {
      setOpen(false);
      return;
    }
    try {
      const res = await api.get('/api/game/available-skills');
      setSkills(res.data.skills || []);
      setLoaded(true);
      setOpen(true);
    } catch (err) {
      console.error('Failed to load skills:', err);
    }
  };

  const handleUse = (skillId: string) => {
    setOpen(false);
    onAction(`skill:${skillId}`);
  };

  return (
    <div style={{ position: 'relative' }}>
      <GameButton
        variant="info"
        onClick={loadSkills}
        disabled={disabled}
        style={{ width: '100%' }}
      >
        ⚔️ {t('combat.actions.abilities', 'Abilities')}
      </GameButton>
      {open && skills.length > 0 && (
        <GameDropdown
          isOpen={open}
          onClose={() => setOpen(false)}
          width="250px"
        >
          {skills.map(s => {
            const onCooldown = (s.current_cooldown || 0) > 0;
            const notEnoughStamina = playerStamina !== undefined && playerStamina < s.stamina_cost;
            const isSkillDisabled = disabled || onCooldown || notEnoughStamina;

            return (
              <GameButton
                key={s.id}
                variant="secondary"
                size="sm"
                onClick={() => handleUse(s.id)}
                disabled={isSkillDisabled}
                style={{ width: '100%', justifyContent: 'flex-start', marginBottom: '4px' }}
              >
                <div style={{ display: 'flex', alignItems: 'center', width: '100%', gap: '0.4rem', filter: isSkillDisabled ? 'grayscale(100%)' : 'none' }}>
                  <span style={{ fontSize: '1rem' }}>{s.icon}</span>
                  <span style={{ flex: 1, textAlign: 'left', color: isSkillDisabled ? '#808090' : '#d0d0e0' }}>{getTranslatedText(s.name)}</span>
                  {onCooldown ? (
                    <span style={{ color: '#e53e3e', fontSize: '0.65rem', fontWeight: 'bold' }}>⏳ {s.current_cooldown}T</span>
                  ) : (
                    <span style={{ color: notEnoughStamina ? '#e53e3e' : '#a0a0b0', fontSize: '0.65rem' }}>⚡{s.stamina_cost}</span>
                  )}
                </div>
              </GameButton>
            );
          })}
        </GameDropdown>
      )}
      {open && skills.length === 0 && loaded && (
        <GameDropdown
          isOpen={open}
          onClose={() => setOpen(false)}
          width="200px"
        >
          <div style={{
            padding: '0.5rem',
            color: '#8a8a9a',
            fontSize: '0.75rem',
            textAlign: 'center',
          }}>
            {t('combat.noSkills', 'No skills available')}
          </div>
        </GameDropdown>
      )}
    </div>
  );
};
