// packages/feature_game_finddiff/lib/screens/finddiff_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/finddiff_controller.dart';
import '../models/finddiff_models.dart';

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

  @override
  State<FindDiffGameScreen> createState() => _FindDiffGameScreenState();
}

class _FindDiffGameScreenState extends State<FindDiffGameScreen> {
  bool _isDialogShowing = false;

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

  void _showGameGuide() {
    final controller = context.read<FindDiffController>();
    
    String message = "화면에 있는 그림들 중\n나머지와 '다른 하나'를 찾으세요.";
    if (controller.difficulty.diffType == FindDiffType.color) {
      message += "\n(색상이 다릅니다)";
    } else if (controller.difficulty.diffType == FindDiffType.icon) {
      message += "\n(모양이 다릅니다)";
    } else {
      message += "\n(각도가 다릅니다)";
    }

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

  void _showGameCompletion(FindDiffController controller) async {
    String formatScore(int primary, int? secondary) {
      return '성공: $primary문제 / 오답: ${secondary ?? 0}회';
    }

    Future<void> saveProgress(String playerName) async {
      // 10문제 이상 맞춰야 성공으로 인정
      if (controller.score < 10) return;

      final identityService = IdentityService();
      final int currentMaxLevel = await identityService.getMaxUnlockedLevel(gameType: 'FIND_DIFF'); // IdentityService에 키 추가 필요
      if (currentMaxLevel < 99) {
        if (controller.difficulty.levelIndex >= currentMaxLevel) {
          int nextLevel = controller.difficulty.levelIndex + 1;
          if (nextLevel > FindDiffDifficulties.allDifficulties.length) {
            await identityService.saveMaxUnlockedLevel(99, gameType: 'FIND_DIFF');
          } else {
            await identityService.saveMaxUnlockedLevel(nextLevel, gameType: 'FIND_DIFF');
          }
        }
      }
    }
    
    await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => GameCompletionScreen(
          args: GameResultArgs(
            gameType: 'FIND_DIFF',
            contextId: controller.difficulty.contextId,
            primaryScore: controller.score,
            secondaryScore: controller.incorrectCount,
            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<FindDiffController>();
    final theme = Theme.of(context);

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

    // 시간 임박 경고 색상
    final Color timeColor = controller.remainingTime <= 3 ? 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: 24, fontWeight: FontWeight.bold, color: timeColor),
              ),
            ),
          ),
        ],
      ),
      body: Column(
        children: [
          // 정보 바
          Padding(
            padding: const EdgeInsets.all(12.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Text("목표: ${controller.score}/10", style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: theme.primaryColor)),
                Text("오답: ${controller.incorrectCount}", style: const TextStyle(fontSize: 16, color: Colors.grey)),
              ],
            ),
          ),
          
          // 피드백 오버레이
          if (controller.showFeedback)
            Expanded(
              child: Center(
                child: Icon(
                  controller.isLastAnswerCorrect ? Icons.check_circle : Icons.cancel,
                  size: 100,
                  color: controller.isLastAnswerCorrect ? Colors.green : theme.colorScheme.error,
                ),
              ),
            )
          else
            // 게임 그리드
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: LayoutBuilder(
                  builder: (context, constraints) {
                    return GridView.builder(
                      itemCount: controller.items.length,
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: controller.difficulty.cols,
                        crossAxisSpacing: 8,
                        mainAxisSpacing: 8,
                        childAspectRatio: 1.0,
                      ),
                      itemBuilder: (context, index) {
                        return _buildItem(controller.items[index], controller);
                      },
                    );
                  },
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildItem(FindDiffItem item, FindDiffController controller) {
    return GestureDetector(
      onTap: () => controller.onItemTapped(item),
      child: Container(
        decoration: BoxDecoration(
          color: Colors.grey.shade200,
          borderRadius: BorderRadius.circular(8),
          border: Border.all(color: Colors.black12),
        ),
        child: Transform.rotate(
          angle: item.angle,
          child: Icon(
            item.icon,
            size: 40, // 동적 크기 조절이 필요하면 LayoutBuilder 활용 가능
            color: item.color,
          ),
        ),
      ),
    );
  }
}