// packages/feature_game_spider/lib/controllers/spider_game_controller.dart
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:service_api/service_api.dart';
import '../models/spider_card.dart';
import '../models/spider_difficulty.dart';
import '../models/spider_game_state.dart';

class SpiderGameController with ChangeNotifier {
  late final SpiderDifficulty difficulty;
  late final String userId;
  late final String? userName;

  late SpiderGameState _currentState;
  SpiderGameState get currentState => _currentState;
  final List<SpiderGameHistory> _undoHistory = [];

  Timer? _timer;
  int _secondsElapsed = 0;
  int get secondsElapsed => _secondsElapsed;

  bool _isGameCompleted = false;
  bool get isGameCompleted => _isGameCompleted;

  List<SpiderCard> _draggedCards = [];
  List<SpiderCard> get draggedCards => _draggedCards;

  int _undoCount = 0;
  int get undoCount => _undoCount;
  static const int maxUndoCount = 5;

  List<SpiderCard> _cardsToDealAnimate = [];
  List<SpiderCard> get cardsToDealAnimate => _cardsToDealAnimate;

  void clearDealAnimationTrigger() {
    debugPrint(
        "[LOG] clearDealAnimationTrigger: CALLED. Clearing animation queue (Current count: ${_cardsToDealAnimate.length}).");
    _cardsToDealAnimate.clear();
  }

  List<SpiderCard> _cardsToAnimateStack = [];
  List<SpiderCard> get cardsToAnimateStack => _cardsToAnimateStack;
  int _animationSourcePileIndex = -1;
  int get animationSourcePileIndex => _animationSourcePileIndex;
  int _animationTargetFoundationIndex = -1;
  int get animationTargetFoundationIndex => _animationTargetFoundationIndex;

  bool get canUndo {
    return _undoHistory.isNotEmpty &&
        !_isGameCompleted &&
        _undoCount < maxUndoCount;
  }

  void setUserInfo(String userId, String? userName) {
    this.userId = userId;
    this.userName = userName;
  }

  void startNewGame(SpiderDifficulty difficulty) {
    this.difficulty = difficulty;
    _undoHistory.clear();
    _isGameCompleted = false;
    _undoCount = 0;
    _cardsToDealAnimate = [];
    _cardsToAnimateStack = [];

    final List<SpiderCard> deck = _createDeck(difficulty.numSuits);
    deck.shuffle(Random());
    final (List<List<SpiderCard>> tableau, List<SpiderCard> stock) =
        _dealCards(deck, difficulty.numCardsDistribution);

    _currentState = SpiderGameState(
      tableau: tableau,
      stock: stock,
      foundation: [], // 👈 비어있는 리스트
      moves: 0,
    );
    _startTimer();
    notifyListeners();
  }

  void restartGame() {
    startNewGame(difficulty);
  }

  // ( _createDeck, _dealCards, _startTimer, stopTimer 는 동일 )
  List<SpiderCard> _createDeck(int numSuits) {
    final List<SpiderSuit> suitsToUse =
        SpiderSuit.values.take(numSuits).toList();
    final List<SpiderCard> deck = [];
    int cardId = 0;
    final int setsPerSuit = (104 / 13) ~/ numSuits;
    for (int i = 0; i < setsPerSuit; i++) {
      for (final suit in suitsToUse) {
        for (int rank = 1; rank <= 13; rank++) {
          deck.add(SpiderCard(id: cardId++, suit: suit, rank: rank));
        }
      }
    }
    return deck;
  }

  (List<List<SpiderCard>>, List<SpiderCard>) _dealCards(
      List<SpiderCard> shuffledDeck, String distribution) {
    final List<List<SpiderCard>> tableau = List.generate(10, (_) => []);
    final List<SpiderCard> stock = List.from(shuffledDeck);
    final parts = distribution.split(',');
    final int longStacksCount = 4;
    final int longStackSize = int.parse(parts[0]);
    final int shortStackSize = int.parse(parts[1]);
    for (int i = 0; i < 10; i++) {
      final int stackSize = (i < longStacksCount) ? longStackSize : shortStackSize;
      for (int j = 0; j < stackSize; j++) {
        tableau[i].add(stock.removeLast());
      }
      if (tableau[i].isNotEmpty) {
        tableau[i].last.isFaceUp = true;
      }
    }
    return (tableau, stock);
  }

  void _startTimer() {
    _timer?.cancel();
    _secondsElapsed = 0;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      _secondsElapsed++;
      notifyListeners();
    });
  }

  void stopTimer() {
    _timer?.cancel();
  }

  /// 🔽 덱 분배 (애니메이션 트리거)
  void dealFromStock() {
    debugPrint("[LOG] dealFromStock: CALLED. Checking conditions...");

    if (_currentState.stock.isEmpty) {
      debugPrint("[LOG] dealFromStock: FAILED (Stock is empty)");
      return;
    }
    if (_isGameCompleted) {
      debugPrint("[LOG] dealFromStock: FAILED (Game completed)");
      return;
    }
    if (_cardsToDealAnimate.isNotEmpty) {
      debugPrint("[LOG] dealFromStock: FAILED (Animation already in progress)");
      return;
    }
    if (_draggedCards.isNotEmpty) {
      debugPrint("[LOG] dealFromStock: FAILED (A card drag is in progress)");
      return;
    }

    final bool hasEmptyPile = _currentState.tableau.any((pile) => pile.isEmpty);
    debugPrint(
        "[LOG] dealFromStock: Checking for empty piles... Result: $hasEmptyPile");

    if (hasEmptyPile) {
      debugPrint("[LOG] dealFromStock: FAILED (Empty pile found)");
      return;
    }

    debugPrint("[LOG] dealFromStock: All checks passed. Saving undo state.");
    _saveUndoState();

    final int cardsToDealCount = min(10, _currentState.stock.length);
    debugPrint(
        "[LOG] dealFromStock: Preparing ${cardsToDealCount} cards for animation.");

    for (int i = 0; i < cardsToDealCount; i++) {
      _cardsToDealAnimate.add(_currentState.stock.removeLast());
    }

    debugPrint(
        "[LOG] dealFromStock: Cards moved to _cardsToDealAnimate queue (Total: ${_cardsToDealAnimate.length}). Notifying listeners...");
    notifyListeners();
  }

  /// 🔽 덱 분배 애니메이션이 끝난 후 UI가 호출
  void finalizeDealFromStock(List<SpiderCard> dealtCards) {
    debugPrint(
        "[LOG] finalizeDealFromStock: CALLED. Finalizing ${dealtCards.length} cards.");

    for (int i = 0; i < dealtCards.length; i++) {
      final card = dealtCards[i];
      card.isFaceUp = true;
      _currentState.tableau[i].add(card);
    }

    _currentState = _currentState.copyWith(moves: _currentState.moves + 1);

    debugPrint(
        "[LOG] finalizeDealFromStock: FINISHED. Calling _checkCompletedStacks...");
    _checkCompletedStacks();
  }

  // ( onDragStarted, onDragCancelled, onCardsDropped, _moveCards 는 동일 )
  void onDragStarted(List<SpiderCard> cards) {
    _draggedCards = cards;
    for (var card in cards) {
      card.isBeingDragged = true;
    }
    notifyListeners();
  }

  void onDragCancelled() {
    for (var card in _draggedCards) {
      card.isBeingDragged = false;
    }
    _draggedCards = [];
    notifyListeners();
  }

  void onCardsDropped(List<SpiderCard> cards, int targetPileIndex) {
    final int sourcePileIndex = _findPileIndexForCard(cards.first);
    for (var card in cards) {
      card.isBeingDragged = false;
    }
    _draggedCards = [];
    _moveCards(cards, sourcePileIndex, targetPileIndex);
  }

  void _moveCards(List<SpiderCard> cards, int fromIndex, int toIndex) {
    if (fromIndex == toIndex) {
      notifyListeners();
      return;
    }
    _saveUndoState();
    final sourcePile = _currentState.tableau[fromIndex];
    sourcePile.removeRange(sourcePile.length - cards.length, sourcePile.length);
    if (sourcePile.isNotEmpty && !sourcePile.last.isFaceUp) {
      sourcePile.last.isFaceUp = true;
    }
    final targetPile = _currentState.tableau[toIndex];
    targetPile.addAll(cards);
    _currentState = _currentState.copyWith(moves: _currentState.moves + 1);
    _checkCompletedStacks();
  }

  int undo() {
    if (!canUndo) return _undoCount;

    final prevState = _undoHistory.removeLast();
    _currentState = SpiderGameState.fromHistory(prevState);
    _undoCount++;
    notifyListeners();
    return _undoCount;
  }

  // ( canPickUpCard, getDraggableStack, isValidMove 는 동일 )
  bool canPickUpCard(SpiderCard card) {
    for (final pile in _currentState.tableau) {
      if (pile.isNotEmpty && pile.last == card) return true;
    }
    return false;
  }

  List<SpiderCard> getDraggableStack(SpiderCard tappedCard) {
    final int pileIndex = _findPileIndexForCard(tappedCard);
    if (pileIndex == -1) return [];
    final pile = _currentState.tableau[pileIndex];
    final int cardIndex = pile.indexOf(tappedCard);
    if (cardIndex == -1 || !tappedCard.isFaceUp) return [];
    final List<SpiderCard> draggableStack = [tappedCard];
    for (int i = cardIndex + 1; i < pile.length; i++) {
      final prevCard = pile[i - 1];
      final currentCard = pile[i];
      if (currentCard.isFaceUp &&
          prevCard.rank == currentCard.rank + 1 &&
          prevCard.suit == currentCard.suit) {
        draggableStack.add(currentCard);
      } else {
        return [];
      }
    }
    return draggableStack;
  }

  bool isValidMove(List<SpiderCard> cardsToMove, int targetPileIndex) {
    if (cardsToMove.isEmpty) return false;
    final targetPile = _currentState.tableau[targetPileIndex];
    if (targetPile.isEmpty) return true;
    final SpiderCard topCardToMove = cardsToMove.first;
    final SpiderCard targetTopCard = targetPile.last;
    return topCardToMove.rank == targetTopCard.rank - 1;
  }

  /// 🔽 _checkCompletedStacks (애니메이션 트리거)
  void _checkCompletedStacks() {
    // 🔽 [수정] 애니메이션이 실행 중이면 중복 검사 방지
    if (_cardsToAnimateStack.isNotEmpty) return;

    bool stackCompleted = false;
    for (int i = 0; i < _currentState.tableau.length; i++) {
      final pile = _currentState.tableau[i];
      if (pile.length < 13) continue;

      final List<SpiderCard> last13Cards = pile.sublist(pile.length - 13);
      bool isComplete = true;
      final SpiderSuit targetSuit = last13Cards.first.suit;
      for (int j = 0; j < 13; j++) {
        final card = last13Cards[j];
        if (!card.isFaceUp || card.suit != targetSuit || card.rank != (13 - j)) {
          isComplete = false;
          break;
        }
      }

      if (isComplete) {
        // 🔽 [수정] 컨트롤러의 큐에만 추가 (인덱스 저장)
        _cardsToAnimateStack = last13Cards;
        _animationSourcePileIndex = i;
        _animationTargetFoundationIndex = _currentState.foundation.length;

        stackCompleted = true;
        break;
      }
    }

    if (stackCompleted) {
      notifyListeners(); // 👈 UI에 애니메이션을 그리라고 알림
    } else {
      _checkGameCompletion();
    }
  }

  /// 🔽 [수정] 스택 완성 애니메이션이 끝난 후 UI가 호출 (인자 받도록 변경)
  void finalizeStackCompletion(
      List<SpiderCard> cardsToAnimate, int sourceIndex) {
    debugPrint(
        "[LOG] finalizeStackCompletion: CALLED. Source Index: $sourceIndex");

    // 🔽 [수정] 크래시 방지
    if (sourceIndex < 0 || sourceIndex >= _currentState.tableau.length) {
      debugPrint(
          "[LOG] finalizeStackCompletion: FAILED. Invalid Source Index: $sourceIndex");
      return;
    }

    _currentState.foundation.add(cardsToAnimate);
    final pile = _currentState.tableau[sourceIndex];

    if (pile.length >= cardsToAnimate.length) {
      pile.removeRange(pile.length - cardsToAnimate.length, pile.length);
    } else {
      debugPrint(
          "[LOG] finalizeStackCompletion: WARNING. Pile length was ${pile.length}, expected >= ${cardsToAnimate.length}.");
    }

    if (pile.isNotEmpty && !pile.last.isFaceUp) {
      pile.last.isFaceUp = true;
    }

    // 🔽 [삭제] 인덱스 리셋 불필요 (지역 변수로 처리됨)
    // _animationSourcePileIndex = -1;
    // _animationTargetFoundationIndex = -1;

    _checkGameCompletion(); // 👈 [핵심] 게임 완료 검사
  }

  // 🔽 [복원됨]
  void clearStackAnimationTrigger() {
    debugPrint(
        "[LOG] clearStackAnimationTrigger: CALLED. Clearing animation queue (Current count: ${_cardsToAnimateStack.length}).");
    _cardsToAnimateStack.clear();
  }

  void _checkGameCompletion() {
    if (_currentState.foundation.length == 8 && !_isGameCompleted) {
      _isGameCompleted = true;
      stopTimer();
      debugPrint(
          "게임 완료! 이동: ${_currentState.moves}, 시간: $_secondsElapsed");
      notifyListeners(); // 👈 [수정] 게임이 '완료'되었을 때만 notify
    } else if (!_isGameCompleted) {
      // 🔽 [수정] 게임이 완료되지 '않았을' 때도 notify (카드 이동 등을 반영하기 위해)
      notifyListeners();
    }
    // (게임이 완료된 후에는 더 이상 notify하지 않음)
  }

  // ( _saveUndoState, _findPileIndexForCard 는 동일 )
  void _saveUndoState() {
    _undoHistory.add(SpiderGameHistory.fromState(_currentState));
    if (_undoHistory.length > 20) {
      _undoHistory.removeAt(0);
    }
  }

  int _findPileIndexForCard(SpiderCard card) {
    return _currentState.tableau.indexWhere((pile) => pile.contains(card));
  }

  // ❌ [삭제] submitRank 메서드 (약 20줄) 삭제
  // Future<RankSubmissionResult> submitRank(String playerName) async { ... }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }
}

extension GameStateCopyWith on SpiderGameState {
  SpiderGameState copyWith({
    List<List<SpiderCard>>? tableau,
    List<SpiderCard>? stock,
    List<List<SpiderCard>>? foundation,
    int? moves,
  }) {
    return SpiderGameState(
      tableau: tableau ?? this.tableau,
      stock: stock ?? this.stock,
      foundation: foundation ?? this.foundation,
      moves: moves ?? this.moves,
    );
  }
}