import 'dart:async'; // 👈 [추가] Timer
import 'package:flutter/material.dart';
import 'package:service_api/service_api.dart'; 
import 'math_quiz_generator.dart';
import '../models/math_quiz_models.dart';

class MathQuizController with ChangeNotifier {
  late final MathQuizDifficulty difficulty;
  late final MathQuizPuzzle puzzle;
  late final String userId;
  late final String? userName;

  late List<String?> _userAnswers;
  List<String?> get userAnswers => _userAnswers;

  int _selectedBlankIndex = 0;
  int get selectedBlankIndex => _selectedBlankIndex;

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

  // 🔽 [추가] 타이머 및 시간
  Timer? _timer;
  int _secondsElapsed = 0;
  int get secondsElapsed => _secondsElapsed;
  
  // 🔽 [추가] 컨트롤러가 제거될 때 타이머 해제
  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  // 🔽 [추가] 타이머 시작
  void _startTimer() {
    _timer?.cancel();
    _secondsElapsed = 0;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      _secondsElapsed++;
      notifyListeners(); // 매초 UI 갱신 (시간 표시용)
    });
  }

  // 🔽 [추가] 타이머 정지
  void _stopTimer() {
    _timer?.cancel();
  }

  /// 1. 로비에서 호출: 새 게임 시작
  void startNewGame(MathQuizDifficulty level, String userId, String? userName) {
    this.difficulty = level;
    this.userId = userId;
    this.userName = userName;

    final generator = MathQuizGenerator();
    this.puzzle = generator.generatePuzzle(level);

    _userAnswers = List.generate(puzzle.solutions.length, (_) => null);
    _selectedBlankIndex = 0;
    _isGameCompleted = false;
    
    _startTimer(); // 👈 [추가]
    
    notifyListeners();
  }

  /// 2. UI(빈칸)에서 호출: 빈칸 선택
  void onBlankTapped(int index) {
    if (_isGameCompleted) return;
    
    _selectedBlankIndex = index;
    notifyListeners();
  }

  /// 3. UI(숫자 버튼)에서 호출: 답 입력
  void onOptionTapped(String option) {
    if (_isGameCompleted) return;

    _userAnswers[_selectedBlankIndex] = option;
    _selectNextBlank();
    notifyListeners();
    _checkCompletion();
  }
  
  /// 4. UI(지우기 버튼)에서 호출: 답 지우기
  void onClearTapped() {
    if (_isGameCompleted) return;
    _userAnswers[_selectedBlankIndex] = null;
    notifyListeners();
  }

  /// 다음 빈칸 (아직 답이 없는)으로 자동 이동
  void _selectNextBlank() {
    int nextIndex = (_selectedBlankIndex + 1) % _userAnswers.length;
    for (int i = 0; i < _userAnswers.length; i++) {
      if (_userAnswers[nextIndex] == null) {
        _selectedBlankIndex = nextIndex;
        return;
      }
      nextIndex = (nextIndex + 1) % _userAnswers.length;
    }
  }

  /// 모든 답이 채워졌는지, 그리고 정답인지 확인
  void _checkCompletion() {
    if (_userAnswers.any((answer) => answer == null)) {
      return; 
    }

    bool allCorrect = true;
    for (int i = 0; i < puzzle.solutions.length; i++) {
      if (_userAnswers[i] != puzzle.solutions[i]) {
        allCorrect = false;
        break;
      }
    }

    if (allCorrect) {
      _isGameCompleted = true;
      _stopTimer(); // 👈 [추가]
      notifyListeners();
    } else {
      // [TODO] 오답 처리 (예: 스낵바 표시)
      debugPrint("오답입니다!");
    }
  }
}