import 'package:flutter/material.dart';

import 'package:asciineverdie/data/game_text_l10n.dart' as l10n;
import 'package:asciineverdie/data/skill_data.dart';
import 'package:asciineverdie/src/core/model/game_state.dart';
import 'package:asciineverdie/src/core/model/skill.dart';

/// 스킬 패널 위젯 (Phase 8: 쿨타임 완료 시 빛남 효과)
///
/// 스킬 목록과 쿨타임 상태를 표시
class SkillPanel extends StatefulWidget {
  const SkillPanel({super.key, required this.skillSystem});

  final SkillSystemState skillSystem;

  @override
  State<SkillPanel> createState() => _SkillPanelState();
}

class _SkillPanelState extends State<SkillPanel>
    with SingleTickerProviderStateMixin {
  late AnimationController _glowController;
  late Animation<double> _glowAnimation;

  // 이전 쿨타임 완료 상태 추적
  final Map<String, bool> _previousReadyState = {};

  @override
  void initState() {
    super.initState();

    _glowController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );

    _glowAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _glowController, curve: Curves.easeInOut),
    );
  }

  @override
  void didUpdateWidget(SkillPanel oldWidget) {
    super.didUpdateWidget(oldWidget);
    _checkCooldownCompletion();
  }

  void _checkCooldownCompletion() {
    // 쿨타임 완료된 스킬이 있으면 glow 애니메이션 시작
    for (final skillState in widget.skillSystem.skillStates) {
      final skill = _getSkillById(skillState.skillId);
      if (skill == null) continue;

      final isReady = skillState.isReady(
        widget.skillSystem.elapsedMs,
        skill.cooldownMs,
      );
      final wasReady = _previousReadyState[skillState.skillId] ?? true;

      // 쿨타임 완료 전환 감지
      if (isReady && !wasReady) {
        _glowController
          ..reset()
          ..repeat(reverse: true);

        // 2초 후 glow 중지
        Future.delayed(const Duration(seconds: 2), () {
          if (mounted) {
            _glowController.stop();
            _glowController.reset();
          }
        });
      }

      _previousReadyState[skillState.skillId] = isReady;
    }
  }

  Skill? _getSkillById(String id) {
    return SkillData.allSkills.where((s) => s.id == id).firstOrNull;
  }

  @override
  void dispose() {
    _glowController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final skillStates = widget.skillSystem.skillStates;

    if (skillStates.isEmpty) {
      return Center(
        child: Text(l10n.uiNoSkills, style: const TextStyle(fontSize: 16)),
      );
    }

    return ListView.builder(
      itemCount: skillStates.length,
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      itemBuilder: (context, index) {
        final skillState = skillStates[index];
        final skill = _getSkillById(skillState.skillId);
        if (skill == null) return const SizedBox.shrink();

        final isReady = skillState.isReady(
          widget.skillSystem.elapsedMs,
          skill.cooldownMs,
        );
        final remainingMs = skillState.remainingCooldown(
          widget.skillSystem.elapsedMs,
          skill.cooldownMs,
        );

        return _SkillRow(
          skill: skill,
          rank: skillState.rank,
          isReady: isReady,
          remainingMs: remainingMs,
          glowAnimation: _glowAnimation,
        );
      },
    );
  }
}

/// 개별 스킬 행 위젯
class _SkillRow extends StatelessWidget {
  const _SkillRow({
    required this.skill,
    required this.rank,
    required this.isReady,
    required this.remainingMs,
    required this.glowAnimation,
  });

  final Skill skill;
  final int rank;
  final bool isReady;
  final int remainingMs;
  final Animation<double> glowAnimation;

  @override
  Widget build(BuildContext context) {
    final cooldownText = isReady
        ? l10n.uiReady
        : '${(remainingMs / 1000).toStringAsFixed(1)}s';

    final skillIcon = _getSkillIcon(skill.type);
    final skillColor = _getSkillColor(skill.type);
    final elementColor = _getElementColor(skill.element);
    final elementIcon = _getElementIcon(skill.element);

    Widget row = Container(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: Row(
        children: [
          // 스킬 타입 아이콘
          Icon(skillIcon, size: 14, color: skillColor),

          // 속성 아이콘 (있는 경우)
          if (skill.element != null) ...[
            const SizedBox(width: 2),
            _ElementBadge(
              icon: elementIcon,
              color: elementColor,
              isDot: skill.isDot,
            ),
          ],

          const SizedBox(width: 4),

          // 스킬 이름 (속성 색상 적용)
          Expanded(
            child: Text(
              skill.name,
              style: TextStyle(
                fontSize: 15,
                color: isReady
                    ? (skill.element != null ? elementColor : Colors.white)
                    : Colors.grey,
              ),
              overflow: TextOverflow.ellipsis,
            ),
          ),

          // DOT 표시
          if (skill.isDot) ...[
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 3, vertical: 1),
              decoration: BoxDecoration(
                color: elementColor.withValues(alpha: 0.3),
                borderRadius: BorderRadius.circular(3),
              ),
              child: Text(
                l10n.uiDot,
                style: const TextStyle(fontSize: 15, color: Colors.white70),
              ),
            ),
            const SizedBox(width: 4),
          ],

          // 랭크
          Text(
            l10n.uiLevel(rank),
            style: const TextStyle(fontSize: 15, color: Colors.grey),
          ),
          const SizedBox(width: 4),
          // 쿨타임 상태
          SizedBox(
            width: 40,
            child: Text(
              cooldownText,
              style: TextStyle(
                fontSize: 15,
                color: isReady ? Colors.green : Colors.orange,
                fontWeight: isReady ? FontWeight.bold : FontWeight.normal,
              ),
              textAlign: TextAlign.right,
            ),
          ),
        ],
      ),
    );

    // 쿨타임 완료 시 glow 효과
    if (isReady) {
      return AnimatedBuilder(
        animation: glowAnimation,
        builder: (context, child) {
          return Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4),
              boxShadow: [
                BoxShadow(
                  color: skillColor.withValues(
                    alpha: glowAnimation.value * 0.5,
                  ),
                  blurRadius: 8 * glowAnimation.value,
                  spreadRadius: 2 * glowAnimation.value,
                ),
              ],
            ),
            child: child,
          );
        },
        child: row,
      );
    }

    return row;
  }

  IconData _getSkillIcon(SkillType type) {
    switch (type) {
      case SkillType.attack:
        return Icons.flash_on;
      case SkillType.heal:
        return Icons.healing;
      case SkillType.buff:
        return Icons.arrow_upward;
      case SkillType.debuff:
        return Icons.arrow_downward;
    }
  }

  Color _getSkillColor(SkillType type) {
    switch (type) {
      case SkillType.attack:
        return Colors.red;
      case SkillType.heal:
        return Colors.green;
      case SkillType.buff:
        return Colors.blue;
      case SkillType.debuff:
        return Colors.purple;
    }
  }

  /// 속성별 색상
  Color _getElementColor(SkillElement? element) {
    if (element == null) return Colors.grey;

    return switch (element) {
      SkillElement.logic => Colors.cyan,
      SkillElement.memory => Colors.purple.shade300,
      SkillElement.network => Colors.teal,
      SkillElement.fire => Colors.orange,
      SkillElement.ice => Colors.lightBlue.shade200,
      SkillElement.lightning => Colors.yellow.shade600,
      SkillElement.voidElement => Colors.deepPurple,
      SkillElement.chaos => Colors.pink,
    };
  }

  /// 속성별 아이콘
  IconData _getElementIcon(SkillElement? element) {
    if (element == null) return Icons.circle;

    return switch (element) {
      SkillElement.logic => Icons.code,
      SkillElement.memory => Icons.memory,
      SkillElement.network => Icons.lan,
      SkillElement.fire => Icons.local_fire_department,
      SkillElement.ice => Icons.ac_unit,
      SkillElement.lightning => Icons.bolt,
      SkillElement.voidElement => Icons.remove_circle_outline,
      SkillElement.chaos => Icons.shuffle,
    };
  }
}

/// 속성 배지 위젯
class _ElementBadge extends StatelessWidget {
  const _ElementBadge({
    required this.icon,
    required this.color,
    this.isDot = false,
  });

  final IconData icon;
  final Color color;
  final bool isDot;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 14,
      height: 14,
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.3),
        borderRadius: BorderRadius.circular(3),
        border: isDot
            ? Border.all(color: color.withValues(alpha: 0.7), width: 1)
            : null,
      ),
      child: Icon(icon, size: 10, color: color),
    );
  }
}
