import 'package:flutter/material.dart';

import 'package:asciineverdie/data/game_text_l10n.dart' as game_l10n;
import 'package:asciineverdie/l10n/app_localizations.dart';
import 'package:asciineverdie/src/shared/animation/ascii_animation_type.dart';
import 'package:asciineverdie/src/shared/animation/monster_size.dart';
import 'package:asciineverdie/src/core/model/combat_event.dart';
import 'package:asciineverdie/src/core/model/game_state.dart';
import 'package:asciineverdie/src/core/model/monster_grade.dart';
import 'package:asciineverdie/src/features/game/widgets/ascii_animation_card.dart';

/// 상단 패널: ASCII 애니메이션 + Task Progress 바
///
/// Phase 7: colorTheme 제거됨, 고정 4색 팔레트 사용
class TaskProgressPanel extends StatelessWidget {
  const TaskProgressPanel({
    super.key,
    required this.progress,
    required this.speedMultiplier,
    required this.onSpeedCycle,
    required this.isPaused,
    required this.onPauseToggle,
    this.specialAnimation,
    this.weaponName,
    this.shieldName,
    this.characterLevel,
    this.monsterLevel,
    this.monsterGrade,
    this.monsterSize,
    this.latestCombatEvent,
    this.raceId,
  });

  final ProgressState progress;
  final int speedMultiplier;
  final VoidCallback onSpeedCycle;

  /// 일시 정지 상태
  final bool isPaused;
  final VoidCallback onPauseToggle;

  /// 특수 애니메이션 (레벨업, 퀘스트 완료 등)
  final AsciiAnimationType? specialAnimation;

  /// 장비 정보 (애니메이션 스타일 결정용)
  final String? weaponName;
  final String? shieldName;
  final int? characterLevel;
  final int? monsterLevel;

  /// 몬스터 등급 (Normal/Elite/Boss) - UI 색상/접두사 표시용
  final MonsterGrade? monsterGrade;

  /// 몬스터 사이즈 (애니메이션 크기 결정용, Act 기반)
  final MonsterSize? monsterSize;

  /// 최근 전투 이벤트 (애니메이션 동기화용, Phase 5)
  final CombatEvent? latestCombatEvent;

  /// 종족 ID (Phase 4: 종족별 캐릭터 애니메이션)
  final String? raceId;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(8),
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.surfaceContainerHighest,
        border: Border(
          bottom: BorderSide(color: Theme.of(context).dividerColor),
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // ASCII 애니메이션 카드 (Phase 7: 고정 4색 팔레트)
          SizedBox(
            height: 120,
            child: AsciiAnimationCard(
              taskType: progress.currentTask.type,
              monsterBaseName: progress.currentTask.monsterBaseName,
              specialAnimation: specialAnimation,
              weaponName: weaponName,
              shieldName: shieldName,
              characterLevel: characterLevel,
              monsterLevel: monsterLevel,
              monsterGrade: monsterGrade,
              monsterSize: monsterSize,
              isPaused: isPaused,
              latestCombatEvent: latestCombatEvent,
              raceId: raceId,
            ),
          ),
          const SizedBox(height: 8),

          // 상태 메시지 + 버튼들 (Phase 7: 테마 버튼 제거됨)
          Row(
            children: [
              _buildPauseButton(context),
              const SizedBox(width: 8),
              Expanded(child: _buildStatusMessage(context)),
              const SizedBox(width: 8),
              _buildSpeedButton(context),
            ],
          ),
          const SizedBox(height: 4),

          // Task Progress 바
          _buildProgressBar(context),
        ],
      ),
    );
  }

  Widget _buildPauseButton(BuildContext context) {
    return SizedBox(
      height: 28,
      child: OutlinedButton(
        onPressed: onPauseToggle,
        style: OutlinedButton.styleFrom(
          padding: const EdgeInsets.symmetric(horizontal: 8),
          visualDensity: VisualDensity.compact,
          side: BorderSide(
            color: isPaused
                ? Colors.orange.withValues(alpha: 0.7)
                : Theme.of(context).colorScheme.outline.withValues(alpha: 0.5),
          ),
        ),
        child: Icon(
          isPaused ? Icons.play_arrow : Icons.pause,
          size: 16,
          color: isPaused ? Colors.orange : null,
        ),
      ),
    );
  }

  Widget _buildSpeedButton(BuildContext context) {
    return SizedBox(
      height: 28,
      child: OutlinedButton(
        onPressed: onSpeedCycle,
        style: OutlinedButton.styleFrom(
          padding: const EdgeInsets.symmetric(horizontal: 8),
          visualDensity: VisualDensity.compact,
        ),
        child: Text(
          '${speedMultiplier}x',
          style: TextStyle(
            fontWeight: speedMultiplier > 1
                ? FontWeight.bold
                : FontWeight.normal,
            color: speedMultiplier > 1
                ? Theme.of(context).colorScheme.primary
                : null,
          ),
        ),
      ),
    );
  }

  /// 상태 메시지 위젯 (등급에 따른 접두사 및 색상 적용)
  Widget _buildStatusMessage(BuildContext context) {
    final message = _getStatusMessage(context);

    // 몬스터 등급에 따른 접두사와 색상
    final grade = monsterGrade;
    final isKillTask = progress.currentTask.type == TaskType.kill;
    final gradePrefix = (isKillTask && grade != null)
        ? grade.displayPrefix
        : '';
    final gradeColorCode = (isKillTask && grade != null)
        ? grade.displayColorCode
        : null;
    final gradeColor = gradeColorCode != null ? Color(gradeColorCode) : null;

    return Text.rich(
      TextSpan(
        children: [
          if (gradePrefix.isNotEmpty)
            TextSpan(
              text: gradePrefix,
              style: TextStyle(color: gradeColor, fontWeight: FontWeight.bold),
            ),
          TextSpan(
            text: message,
            style: gradeColor != null ? TextStyle(color: gradeColor) : null,
          ),
        ],
      ),
      style: Theme.of(context).textTheme.bodyMedium,
      textAlign: TextAlign.center,
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
  }

  /// 현재 상태에 맞는 메시지 반환
  ///
  /// 특수 애니메이션(부활 등) 중에는 해당 메시지 표시
  String _getStatusMessage(BuildContext context) {
    // 부활 애니메이션 중에는 부활 메시지 표시
    if (specialAnimation == AsciiAnimationType.resurrection) {
      return game_l10n.animationResurrecting;
    }

    // 기본: 현재 태스크 캡션 또는 환영 메시지
    if (progress.currentTask.caption.isNotEmpty) {
      return progress.currentTask.caption;
    }
    return L10n.of(context).welcomeMessage;
  }

  Widget _buildProgressBar(BuildContext context) {
    final progressValue = progress.task.max > 0
        ? (progress.task.position / progress.task.max).clamp(0.0, 1.0)
        : 0.0;

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      child: LinearProgressIndicator(
        value: progressValue,
        backgroundColor: Theme.of(
          context,
        ).colorScheme.primary.withValues(alpha: 0.2),
        valueColor: AlwaysStoppedAnimation<Color>(
          Theme.of(context).colorScheme.primary,
        ),
        minHeight: 12,
      ),
    );
  }
}
