// packages/feature_game_cardflip/lib/screens/cardflip_game_screen.dart

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:service_api/service_api.dart';
import 'package:feature_common/feature_common.dart';
import '../controllers/cardflip_controller.dart';
import '../models/cardflip_models.dart';

class CardFlipGameScreen extends StatefulWidget {
  const CardFlipGameScreen({super.key});

  @override
  State<CardFlipGameScreen> createState() => _CardFlipGameScreenState();
}

class _CardFlipGameScreenState extends State<CardFlipGameScreen> {
  bool _isDialogShowing = false;

  static const List<IconData> _iconPool = [
    Icons.home, Icons.favorite, Icons.star, Icons.person, Icons.settings,
    Icons.lock, Icons.map, Icons.camera_alt, Icons.phone, Icons.music_note,
    Icons.flight, Icons.directions_car, Icons.shopping_cart, Icons.visibility,
    Icons.delete, Icons.edit, Icons.share, Icons.wifi, Icons.battery_full,
    Icons.bluetooth, Icons.lightbulb, Icons.wb_sunny, Icons.ac_unit, Icons.access_alarm,
    Icons.android, Icons.apple, Icons.attach_file, Icons.audiotrack, Icons.beach_access,
    Icons.cake, Icons.local_pizza, Icons.local_cafe, Icons.local_florist, Icons.local_shipping
  ];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _showGameGuide();
    });
  }

  void _showGameGuide() {
    final controller = context.read<CardFlipController>();
    final difficulty = controller.difficulty;
    
    String title = "게임 방법";
    String message = "두 장의 카드를 뒤집어\n똑같은 그림을 찾으세요.";

    if (difficulty.contentType == CardContentType.calculation) {
      title = "연산 매칭";
      message = "카드에 적힌 '계산식'과\n그 '정답'을 짝지어주세요.\n\n예: [2 + 3] ↔ [5]";
    } else if (difficulty.contentType == CardContentType.pairWord) {
      title = "연상 매칭";
      message = "서로 관련있는 '짝꿍 단어'를\n찾아주세요.\n\n예: [토끼] ↔ [당근]";
    }

    showDialog(
      context: context,
      barrierDismissible: false, 
      builder: (context) => AlertDialog(
        title: Text(title, style: const TextStyle(fontWeight: FontWeight.bold)),
        content: Text(message, style: const TextStyle(fontSize: 16), textAlign: TextAlign.center),
        actions: [
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
              controller.startGameTimer();
            },
            child: const Text("시작하기"),
          ),
        ],
      ),
    );
  }

  void _showGameCompletion(CardFlipController controller) async {
    // [🔥 수정] 점수 포맷터: secondaryScore를 디코딩하여 표시
    // (secondary = matched * 1000 + (999 - flips))
    String formatScore(int primary, int? secondary) {
      if (secondary == null) return '${primary}초';
      
      final int matched = secondary ~/ 1000;
      final int flips = 999 - (secondary % 1000);
      // (실패 횟수 = (총 뒤집기 - 정답매칭*2) / 2)
      final int mistakes = (flips - (matched * 2)) ~/ 2;
      
      return '시간: ${primary}초 (성공:$matched / 실수:$mistakes)';
    }

    Future<void> saveProgress(String playerName) async {
      if (controller.isTimeOut) return;

      final identityService = IdentityService();
      final int currentMaxLevel = await identityService.getMaxUnlockedLevel(gameType: 'CARD_FLIP');
      if (currentMaxLevel < 99) {
        if (controller.difficulty.levelIndex >= currentMaxLevel) {
          int nextLevel = controller.difficulty.levelIndex + 1;
          if (nextLevel > CardFlipDifficulties.allDifficulties.length) {
            await identityService.saveMaxUnlockedLevel(99, gameType: 'CARD_FLIP');
          } else {
            await identityService.saveMaxUnlockedLevel(nextLevel, gameType: 'CARD_FLIP');
          }
        }
      }
    }

    // [🔥 수정] secondaryScore에 매칭 수와 클릭 수를 함께 인코딩 (정렬을 위해)
    // (많은 매칭 + 적은 클릭일수록 높은 값이 되도록 설계)
    final int encodedScore = (controller.matchedPairsCount * 1000) + (999 - controller.flipCount);
    
    await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => GameCompletionScreen(
          args: GameResultArgs(
            gameType: 'CARD_FLIP',
            contextId: controller.difficulty.contextId,
            primaryScore: controller.remainingTime,
            secondaryScore: encodedScore, // 👈 인코딩된 점수 전달
            userId: controller.userId,
            userName: controller.userName,
            scoreFormatter: formatScore,
            onProgressSave: saveProgress,
          ),
        ),
      ),
    );

    if (mounted && Navigator.canPop(context)) {
      Navigator.pop(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    final controller = context.watch<CardFlipController>();
    final theme = Theme.of(context);

    if (controller.isGameCompleted && !_isDialogShowing) {
      _isDialogShowing = true;
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _showGameCompletion(controller);
      });
    }

    final Color timeColor = controller.remainingTime <= 10 ? theme.colorScheme.error : theme.colorScheme.onSurface;

    return Scaffold(
      appBar: AppBar(
        title: Text(controller.difficulty.name),
        actions: [
          Padding(
            padding: const EdgeInsets.only(right: 16.0),
            child: Center(
              child: Text(
                '${controller.remainingTime}s',
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: timeColor),
              ),
            ),
          ),
        ],
      ),
      body: Column(
        children: [
          // 🔽 [🔥 수정] 상단 정보: 매칭 수 / 시도 횟수 표시
          Padding(
            padding: const EdgeInsets.all(12.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Text(
                  "찾은 짝: ${controller.matchedPairsCount} / ${controller.totalPairsCount}", 
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: theme.primaryColor)
                ),
                Text(
                  "뒤집기: ${controller.flipCount}", 
                  style: const TextStyle(fontSize: 16, color: Colors.grey)
                ),
              ],
            ),
          ),
          
          Expanded(
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: LayoutBuilder(
                builder: (context, constraints) {
                  final crossAxisCount = controller.difficulty.cols;
                  
                  return GridView.builder(
                    itemCount: controller.cards.length,
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: crossAxisCount,
                      childAspectRatio: 0.85,
                      crossAxisSpacing: 8,
                      mainAxisSpacing: 8,
                    ),
                    itemBuilder: (context, index) {
                      return _buildCard(controller.cards[index], controller, theme);
                    },
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCard(CardItem card, CardFlipController controller, ThemeData theme) {
    return GestureDetector(
      onTap: () => controller.onCardTapped(card),
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
        decoration: BoxDecoration(
          color: card.isFaceUp || card.isMatched 
              ? Colors.white 
              : theme.primaryColor, 
          borderRadius: BorderRadius.circular(8),
          border: Border.all(color: Colors.black12),
          boxShadow: [
            BoxShadow(color: Colors.black12, blurRadius: 4, offset: const Offset(2, 2))
          ],
        ),
        child: Center(
          child: (card.isFaceUp || card.isMatched)
              ? _buildCardContent(card)
              : Icon(Icons.help_outline, color: Colors.white.withOpacity(0.5), size: 32),
        ),
      ),
    );
  }

  Widget _buildCardContent(CardItem card) {
    if (card.displayContent.startsWith("ICON_")) {
      final int iconIndex = int.tryParse(card.displayContent.split('_')[1]) ?? 0;
      final IconData icon = _iconPool[iconIndex % _iconPool.length];
      return Icon(icon, size: 40, color: Colors.orange); 
    } else {
      return Padding(
        padding: const EdgeInsets.all(4.0),
        child: FittedBox(
          fit: BoxFit.scaleDown,
          child: Text(
            card.displayContent,
            style: const TextStyle(fontSize: 32, fontWeight: FontWeight.bold),
          ),
        ),
      );
    }
  }
}