import 'package:flutter/material.dart';

import 'package:asciineverdie/l10n/app_localizations.dart';
import 'package:asciineverdie/src/core/engine/item_service.dart';
import 'package:asciineverdie/src/core/model/equipment_item.dart';
import 'package:asciineverdie/src/core/model/equipment_slot.dart';
import 'package:asciineverdie/src/core/model/item_stats.dart';
import 'package:asciineverdie/src/shared/retro_colors.dart';

/// 좌우 대칭 장비 비교 리스트
///
/// 내 장비와 상대 장비를 나란히 표시하고,
/// 선택 시 인라인으로 비교 정보를 확장
class ArenaEquipmentCompareList extends StatefulWidget {
  const ArenaEquipmentCompareList({
    super.key,
    required this.myEquipment,
    required this.enemyEquipment,
    required this.selectedSlot,
    required this.onSlotSelected,
    this.recommendedSlot,
    this.opponentBettingSlot,
  });

  /// 내 장비 목록
  final List<EquipmentItem>? myEquipment;

  /// 상대 장비 목록
  final List<EquipmentItem>? enemyEquipment;

  /// 현재 선택된 슬롯 (내가 상대에게서 뺏을 슬롯)
  final EquipmentSlot? selectedSlot;

  /// 슬롯 선택 콜백
  final ValueChanged<EquipmentSlot> onSlotSelected;

  /// 추천 슬롯 (점수 이득이 가장 큰 슬롯)
  final EquipmentSlot? recommendedSlot;

  /// 상대가 선택한 슬롯 (패배 시 내가 잃을 슬롯)
  final EquipmentSlot? opponentBettingSlot;

  @override
  State<ArenaEquipmentCompareList> createState() =>
      _ArenaEquipmentCompareListState();
}

class _ArenaEquipmentCompareListState extends State<ArenaEquipmentCompareList> {
  /// 현재 확장된 슬롯 (탭하여 비교 중인 슬롯)
  EquipmentSlot? _expandedSlot;

  /// 스크롤 컨트롤러 (자동 스크롤용)
  final ScrollController _scrollController = ScrollController();

  /// 슬롯별 행 높이 (대략적 계산용)
  static const double _rowHeight = 40.0;
  static const double _expandedHeight = 200.0;

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

  /// 선택된 슬롯으로 자동 스크롤
  void _scrollToSlot(EquipmentSlot slot) {
    final index = EquipmentSlot.values.indexOf(slot);
    if (index < 0) return;

    // 현재 확장된 슬롯까지의 높이 계산
    double targetOffset = 0;
    for (int i = 0; i < index; i++) {
      targetOffset += _rowHeight;
      if (_expandedSlot == EquipmentSlot.values[i]) {
        targetOffset += _expandedHeight;
      }
    }

    // 부드럽게 스크롤
    _scrollController.animateTo(
      targetOffset,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeOutCubic,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // 헤더 (좌우 타이틀)
        _buildHeader(context),
        const SizedBox(height: 8),
        // 장비 리스트
        Expanded(
          child: ListView.builder(
            controller: _scrollController,
            itemCount: EquipmentSlot.values.length,
            itemBuilder: (context, index) {
              final slot = EquipmentSlot.values[index];
              return _buildSlotRow(context, slot);
            },
          ),
        ),
      ],
    );
  }

  Widget _buildHeader(BuildContext context) {
    final l10n = L10n.of(context);
    return Row(
      children: [
        // 내 장비 타이틀
        Expanded(
          child: Container(
            padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 8),
            decoration: BoxDecoration(
              color: Colors.blue.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(4),
              border: Border.all(color: Colors.blue.withValues(alpha: 0.3)),
            ),
            child: Text(
              l10n.arenaMyEquipment,
              style: const TextStyle(
                fontFamily: 'PressStart2P',
                fontSize: 11,
                color: Colors.blue,
              ),
              textAlign: TextAlign.center,
            ),
          ),
        ),
        const SizedBox(width: 8),
        // 상대 장비 타이틀
        Expanded(
          child: Container(
            padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 8),
            decoration: BoxDecoration(
              color: Colors.red.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(4),
              border: Border.all(color: Colors.red.withValues(alpha: 0.3)),
            ),
            child: Text(
              l10n.arenaEnemyEquipment,
              style: const TextStyle(
                fontFamily: 'PressStart2P',
                fontSize: 11,
                color: Colors.red,
              ),
              textAlign: TextAlign.center,
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildSlotRow(BuildContext context, EquipmentSlot slot) {
    final myItem = _findItem(slot, widget.myEquipment);
    final enemyItem = _findItem(slot, widget.enemyEquipment);
    final isExpanded = _expandedSlot == slot;
    final isSelected = widget.selectedSlot == slot;
    final isRecommended = widget.recommendedSlot == slot;

    // 무기 슬롯은 선택 불가 (보호됨)
    final isLocked = slot == EquipmentSlot.weapon;

    // 양방향 베팅 상태
    final isMyTarget = isSelected; // 내가 선택 = 상대 장비 획득 예정
    final isOpponentTarget =
        widget.opponentBettingSlot == slot; // 상대가 선택 = 내 장비 손실 예정

    final myScore = myItem != null
        ? ItemService.calculateEquipmentScore(myItem)
        : 0;
    final enemyScore = enemyItem != null
        ? ItemService.calculateEquipmentScore(enemyItem)
        : 0;
    final scoreDiff = enemyScore - myScore;

    return Column(
      children: [
        // 슬롯 행 (좌우 대칭)
        GestureDetector(
          onTap: isLocked
              ? null
              : () {
                  // 탭하면 즉시 선택 + 확장 + 자동 스크롤
                  widget.onSlotSelected(slot);
                  setState(() {
                    _expandedSlot = isExpanded ? null : slot;
                  });
                  // 확장될 때만 스크롤 (다음 프레임에서 실행)
                  if (!isExpanded) {
                    WidgetsBinding.instance.addPostFrameCallback((_) {
                      _scrollToSlot(slot);
                    });
                  }
                },
          child: Container(
            padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 4),
            decoration: BoxDecoration(
              color: isLocked
                  ? RetroColors.borderOf(context).withValues(alpha: 0.1)
                  : isExpanded
                  ? RetroColors.panelBgOf(context)
                  : Colors.transparent,
              border: Border(
                bottom: BorderSide(
                  color: RetroColors.borderOf(context).withValues(alpha: 0.3),
                ),
              ),
            ),
            child: Row(
              children: [
                // 내 장비 (상대가 노리면 빨간 배경)
                Expanded(
                  child: _buildEquipmentCell(
                    context,
                    myItem,
                    myScore,
                    Colors.blue,
                    isLocked: isLocked,
                    isTargetedByOpponent: isOpponentTarget,
                  ),
                ),
                // 슬롯 아이콘 (중앙)
                _buildSlotIndicator(
                  context,
                  slot,
                  isSelected,
                  isRecommended,
                  scoreDiff,
                  isLocked: isLocked,
                  isOpponentTarget: isOpponentTarget,
                ),
                // 상대 장비 (내가 선택하거나 추천이면 녹색 배경)
                Expanded(
                  child: _buildEquipmentCell(
                    context,
                    enemyItem,
                    enemyScore,
                    Colors.red,
                    isLocked: isLocked,
                    isMyTarget: isMyTarget,
                    isRecommended: isRecommended && !isMyTarget,
                  ),
                ),
              ],
            ),
          ),
        ),
        // 확장된 비교 패널 (잠긴 슬롯은 확장 불가)
        if (isExpanded && !isLocked)
          _buildExpandedPanel(context, slot, myItem, enemyItem, scoreDiff),
      ],
    );
  }

  /// 장비 셀 (한쪽)
  ///
  /// [isTargetedByOpponent] 상대가 이 슬롯을 노림 (좌측 - 내 장비 손실)
  /// [isMyTarget] 내가 이 슬롯을 선택함 (우측 - 상대 장비 획득)
  /// [isRecommended] 추천 슬롯 (우측 - 획득 추천)
  Widget _buildEquipmentCell(
    BuildContext context,
    EquipmentItem? item,
    int score,
    Color accentColor, {
    bool isLocked = false,
    bool isTargetedByOpponent = false,
    bool isMyTarget = false,
    bool isRecommended = false,
  }) {
    final hasItem = item != null && item.isNotEmpty;
    final rarityColor = hasItem ? _getRarityColor(item.rarity) : Colors.grey;

    // 배경색 결정
    Color? bgColor;
    Color? borderColor;
    if (!isLocked) {
      if (isTargetedByOpponent) {
        bgColor = Colors.red.withValues(alpha: 0.2); // 손실 예정
        borderColor = Colors.red.withValues(alpha: 0.5);
      } else if (isMyTarget) {
        bgColor = Colors.green.withValues(alpha: 0.25); // 획득 예정
        borderColor = Colors.green.withValues(alpha: 0.6);
      } else if (isRecommended) {
        bgColor = Colors.green.withValues(alpha: 0.15); // 추천
        borderColor = Colors.green.withValues(alpha: 0.4);
      }
    }

    final textColor = isLocked
        ? RetroColors.textMutedOf(context)
        : hasItem
        ? rarityColor
        : RetroColors.textMutedOf(context);

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 6),
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.circular(4),
        border: borderColor != null ? Border.all(color: borderColor) : null,
      ),
      child: Row(
        children: [
          // 아이템 이름
          Expanded(
            child: Text(
              hasItem ? item.name : '-',
              style: TextStyle(
                fontFamily: 'PressStart2P',
                fontSize: 11,
                color: textColor,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          // 점수
          Text(
            '$score',
            style: TextStyle(
              fontFamily: 'PressStart2P',
              fontSize: 11,
              color: isLocked
                  ? RetroColors.textMutedOf(context)
                  : hasItem
                  ? RetroColors.textSecondaryOf(context)
                  : RetroColors.textMutedOf(context),
            ),
          ),
        ],
      ),
    );
  }

  /// 슬롯 인디케이터 (중앙)
  Widget _buildSlotIndicator(
    BuildContext context,
    EquipmentSlot slot,
    bool isSelected,
    bool isRecommended,
    int scoreDiff, {
    bool isLocked = false,
    bool isOpponentTarget = false,
  }) {
    final Color borderColor;
    final Color bgColor;

    if (isLocked) {
      borderColor = RetroColors.borderOf(context).withValues(alpha: 0.5);
      bgColor = RetroColors.borderOf(context).withValues(alpha: 0.1);
    } else if (isSelected && isOpponentTarget) {
      // 양쪽 모두 선택 - 금색 테두리 유지
      borderColor = RetroColors.goldOf(context);
      bgColor = RetroColors.goldOf(context).withValues(alpha: 0.3);
    } else if (isSelected) {
      borderColor = RetroColors.goldOf(context);
      bgColor = RetroColors.goldOf(context).withValues(alpha: 0.3);
    } else if (isOpponentTarget) {
      // 상대만 선택 - 빨간 표시
      borderColor = Colors.red.withValues(alpha: 0.7);
      bgColor = Colors.red.withValues(alpha: 0.15);
    } else if (isRecommended) {
      borderColor = Colors.green;
      bgColor = Colors.green.withValues(alpha: 0.2);
    } else {
      borderColor = RetroColors.borderOf(context);
      bgColor = RetroColors.panelBgOf(context);
    }

    return Container(
      width: 56,
      margin: const EdgeInsets.symmetric(horizontal: 4),
      padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 2),
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.circular(4),
        border: Border.all(color: borderColor, width: isSelected ? 2 : 1),
      ),
      child: Column(
        children: [
          // 슬롯 아이콘
          Icon(
            isLocked ? Icons.lock : _getSlotIcon(slot),
            size: 12,
            color: isLocked
                ? RetroColors.textMutedOf(context)
                : isSelected
                ? RetroColors.goldOf(context)
                : RetroColors.textSecondaryOf(context),
          ),
          const SizedBox(height: 2),
          // 잠금 표시 또는 점수 변화
          if (isLocked)
            Text(
              L10n.of(context).arenaWeaponLocked,
              style: TextStyle(
                fontFamily: 'PressStart2P',
                fontSize: 11,
                color: RetroColors.textMutedOf(context),
              ),
            )
          else
            _buildScoreDiffBadge(context, scoreDiff, isRecommended),
        ],
      ),
    );
  }

  /// 점수 변화 뱃지
  Widget _buildScoreDiffBadge(
    BuildContext context,
    int scoreDiff,
    bool isRecommended,
  ) {
    final Color diffColor;
    final String diffText;

    if (scoreDiff > 0) {
      diffColor = Colors.green;
      diffText = '+$scoreDiff';
    } else if (scoreDiff < 0) {
      diffColor = Colors.red;
      diffText = '$scoreDiff';
    } else {
      diffColor = RetroColors.textMutedOf(context);
      diffText = '±0';
    }

    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        if (isRecommended) ...[
          Text(
            L10n.of(context).arenaRecommended,
            style: const TextStyle(
              fontFamily: 'PressStart2P',
              fontSize: 11,
              color: Colors.green,
            ),
          ),
          const SizedBox(width: 2),
        ],
        Text(
          diffText,
          style: TextStyle(
            fontFamily: 'PressStart2P',
            fontSize: 11,
            color: diffColor,
            fontWeight: FontWeight.bold,
          ),
        ),
      ],
    );
  }

  /// 확장된 비교 패널
  Widget _buildExpandedPanel(
    BuildContext context,
    EquipmentSlot slot,
    EquipmentItem? myItem,
    EquipmentItem? enemyItem,
    int scoreDiff,
  ) {
    final l10n = L10n.of(context);
    final Color resultColor;
    final String resultText;
    final IconData resultIcon;

    if (scoreDiff > 0) {
      resultColor = Colors.green;
      resultText = l10n.arenaScoreGain(scoreDiff);
      resultIcon = Icons.arrow_upward;
    } else if (scoreDiff < 0) {
      resultColor = Colors.red;
      resultText = l10n.arenaScoreLose(scoreDiff);
      resultIcon = Icons.arrow_downward;
    } else {
      resultColor = RetroColors.textMutedOf(context);
      resultText = l10n.arenaEvenTrade;
      resultIcon = Icons.swap_horiz;
    }

    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      padding: const EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: resultColor.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(6),
        border: Border.all(color: resultColor.withValues(alpha: 0.5)),
      ),
      child: Column(
        children: [
          // 상세 비교 (좌우)
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 내 아이템 상세
              Expanded(child: _buildItemDetail(context, myItem, Colors.blue)),
              // VS 아이콘
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 8),
                child: Icon(
                  Icons.swap_horiz,
                  color: RetroColors.textMutedOf(context),
                  size: 20,
                ),
              ),
              // 상대 아이템 상세
              Expanded(child: _buildItemDetail(context, enemyItem, Colors.red)),
            ],
          ),
          const SizedBox(height: 10),
          // 교환 결과
          Container(
            padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 12),
            decoration: BoxDecoration(
              color: resultColor.withValues(alpha: 0.15),
              borderRadius: BorderRadius.circular(4),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(resultIcon, color: resultColor, size: 14),
                const SizedBox(width: 6),
                Text(
                  resultText,
                  style: TextStyle(
                    fontFamily: 'PressStart2P',
                    fontSize: 11,
                    color: resultColor,
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 10),
          // 선택됨 인디케이터 (SELECT 버튼 대신)
          Container(
            padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
            decoration: BoxDecoration(
              color: RetroColors.goldOf(context).withValues(alpha: 0.2),
              borderRadius: BorderRadius.circular(4),
              border: Border.all(color: RetroColors.goldOf(context), width: 2),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(
                  Icons.check_circle,
                  color: RetroColors.goldOf(context),
                  size: 16,
                ),
                const SizedBox(width: 6),
                Text(
                  L10n.of(context).arenaSelected,
                  style: TextStyle(
                    fontFamily: 'PressStart2P',
                    fontSize: 12,
                    color: RetroColors.goldOf(context),
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 아이템 상세 정보
  Widget _buildItemDetail(
    BuildContext context,
    EquipmentItem? item,
    Color accentColor,
  ) {
    final hasItem = item != null && item.isNotEmpty;
    final rarityColor = hasItem ? _getRarityColor(item.rarity) : Colors.grey;
    final score = hasItem ? ItemService.calculateEquipmentScore(item) : 0;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 아이템 이름
        Text(
          hasItem ? item.name : '(Empty)',
          style: TextStyle(
            fontFamily: 'PressStart2P',
            fontSize: 11,
            color: hasItem ? rarityColor : RetroColors.textMutedOf(context),
          ),
          maxLines: 2,
          overflow: TextOverflow.ellipsis,
        ),
        const SizedBox(height: 4),
        // 점수
        Text(
          'Score: $score',
          style: TextStyle(
            fontFamily: 'PressStart2P',
            fontSize: 11,
            color: RetroColors.textSecondaryOf(context),
          ),
        ),
        // 스탯
        if (hasItem) ...[
          const SizedBox(height: 4),
          _buildItemStats(context, item),
        ],
      ],
    );
  }

  /// 아이템 스탯 표시
  Widget _buildItemStats(BuildContext context, EquipmentItem item) {
    final stats = item.stats;
    final statWidgets = <Widget>[];

    if (stats.atk > 0) {
      statWidgets.add(_buildStatChip('ATK', stats.atk, Colors.red));
    }
    if (stats.def > 0) {
      statWidgets.add(_buildStatChip('DEF', stats.def, Colors.blue));
    }
    if (stats.hpBonus > 0) {
      statWidgets.add(_buildStatChip('HP', stats.hpBonus, Colors.green));
    }
    if (stats.mpBonus > 0) {
      statWidgets.add(_buildStatChip('MP', stats.mpBonus, Colors.purple));
    }

    if (statWidgets.isEmpty) return const SizedBox.shrink();

    return Wrap(spacing: 3, runSpacing: 3, children: statWidgets);
  }

  Widget _buildStatChip(String label, int value, Color color) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 3, vertical: 1),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.15),
        borderRadius: BorderRadius.circular(2),
      ),
      child: Text(
        '$label +$value',
        style: TextStyle(
          fontFamily: 'PressStart2P',
          fontSize: 11,
          color: color,
        ),
      ),
    );
  }

  EquipmentItem? _findItem(EquipmentSlot slot, List<EquipmentItem>? items) {
    if (items == null) return null;
    for (final item in items) {
      if (item.slot == slot) return item;
    }
    return null;
  }

  IconData _getSlotIcon(EquipmentSlot slot) {
    return switch (slot) {
      EquipmentSlot.weapon => Icons.gavel,
      EquipmentSlot.shield => Icons.shield,
      EquipmentSlot.helm => Icons.sports_mma,
      EquipmentSlot.hauberk => Icons.checkroom,
      EquipmentSlot.brassairts => Icons.front_hand,
      EquipmentSlot.vambraces => Icons.back_hand,
      EquipmentSlot.gauntlets => Icons.sports_handball,
      EquipmentSlot.gambeson => Icons.dry_cleaning,
      EquipmentSlot.cuisses => Icons.airline_seat_legroom_normal,
      EquipmentSlot.greaves => Icons.snowshoeing,
      EquipmentSlot.sollerets => Icons.do_not_step,
    };
  }

  Color _getRarityColor(ItemRarity rarity) {
    return switch (rarity) {
      ItemRarity.common => Colors.grey.shade600,
      ItemRarity.uncommon => Colors.green.shade600,
      ItemRarity.rare => Colors.blue.shade600,
      ItemRarity.epic => Colors.purple.shade600,
      ItemRarity.legendary => Colors.orange.shade700,
    };
  }
}
