import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'emoX.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: EmotionGame(),
    );
  }
}

class EmotionGame extends StatefulWidget {
  @override
  _EmotionGameState createState() => _EmotionGameState();
}

class _EmotionGameState extends State<EmotionGame> {
  late String correctEmotion;
  bool isCorrect = false;
  int questionIndex = 0;
  bool allQuestionsCompleted =
      false; // Flag to track if all questions are completed

  // Map containing emotions, questions, and corresponding image paths
  final Map<String, Map<String, String>> emotionData = {
    'Sad': {
      'question': 'How Lili looks like if she is Sad?',
      'image': 'gsad.png'
    },
    'Angry': {
      'question': 'How Lili looks like if she is Angry?',
      'image': 'gangry.png'
    },
    'Happy': {
      'question': 'How Lili looks like if she is Happy?',
      'image': 'ghappy.png'
    },
    'Confused': {
      'question': 'How Lili looks like if she is Confused?',
      'image': 'gconfused.png'
    },
    'Surprised': {
      'question': 'How Lili looks like if she is Surprised?',
      'image': 'gsurprised.png'
    },
  };

  // Lists containing shuffled emotions and questions
  late List<String> shuffledEmotions;
  late List<String> shuffledQuestions;

  @override
  void initState() {
    super.initState();
    // Set preferred orientations to portrait mode after navigating to this screen
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    shuffledEmotions = List.from(emotionData.keys)..shuffle();
    shuffledQuestions = List.from(emotionData.values.map((e) => e['question']!))
      ..shuffle();
    correctEmotion = _getCorrectEmotion(shuffledQuestions[questionIndex]);
  }

  // Function to get the correct emotion based on the question
  String _getCorrectEmotion(String question) {
    return emotionData.entries
        .firstWhere((entry) => entry.value['question'] == question)
        .key;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Emotion Game'),
      ),
      body: Column(
        children: [
          Text(
            shuffledQuestions[questionIndex],
            style: TextStyle(
              fontSize: 20.0,
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(height: 60.0),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: shuffledEmotions.map((emotion) {
              return Draggable(
                child: Image.asset(
                  'game_assets/${emotionData[emotion]!['image']}',
                  width: 65,
                  height: 65,
                ),
                feedback: Image.asset(
                  'game_assets/${emotionData[emotion]!['image']}',
                  width: 60,
                  height: 60,
                ),
                data: emotion,
              );
            }).toList(),
          ),
          SizedBox(height: 70.0),
          DragTarget<String>(
            builder: (BuildContext context, List<String?> candidateData,
                List<dynamic> rejectedData) {
              return Container(
                width: 240,
                height: 240,
                color: Color.fromARGB(255, 222, 214, 145).withOpacity(0.5),
                child: isCorrect
                    ? Image.asset(
                        'game_assets/${emotionData[correctEmotion]!['image']}')
                    : null,
              );
            },
            onWillAccept: (data) => data == correctEmotion,
            onAccept: (data) {
              setState(() {
                isCorrect = true;
              });
            },
          ),
          SizedBox(height: 20.0),
          ElevatedButton(
            onPressed: () {
              setState(() {
                if (questionIndex < shuffledQuestions.length - 1) {
                  questionIndex++;
                  isCorrect = false;
                  correctEmotion =
                      _getCorrectEmotion(shuffledQuestions[questionIndex]);
                } else {
                  // Last question, set the flag to true
                  allQuestionsCompleted = true;
                }
              });
            },
            child: Text(
              questionIndex < shuffledQuestions.length - 1
                  ? 'Next Question >>'
                  : 'Finish Game',
            ),
          ),
          if (allQuestionsCompleted)
            SizedBox(
              height: 30,
            ), // Show the text only when all questions are completed
          if (allQuestionsCompleted)
            Text(
              'Game Over! You Won!',
              style: TextStyle(
                color: Color.fromARGB(255, 48, 173, 26),
                fontSize: 20.0,
                fontWeight: FontWeight.bold,
              ),
            ),
          if (allQuestionsCompleted)
            SizedBox(
              height: 10,
            ), // Show the single Quit button only when all questions are completed
          if (allQuestionsCompleted)
            ElevatedButton(
              onPressed: () {
                Navigator.pushReplacement(
                  context,
                  MaterialPageRoute(builder: (context) => LevelScreen()),
                );
              },
              child: Text('Quit'),
              style: ElevatedButton.styleFrom(
                primary: Color.fromARGB(255, 247, 56, 35),
                onPrimary: Colors.white,
              ),
            ),
        ],
      ),
    );
  }
}
