import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.dart';
import 'level2.dart';
import 'level3.dart';
import 'package:mobile_application_kids/games.dart';

void main() {
  runApp(EmoXApp());
}

class EmoXApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: "Emotion Matching Game",
      home: LevelScreen(),
    );
  }
}

class LevelScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('EmoX Game'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => Level1VideoScreen()),
                );
              },
              style: ElevatedButton.styleFrom(
                primary: Colors.transparent,
                elevation: 0,
              ),
              child: Image.asset(
                'game_assets/btn_level1.png',
                width: 350,
                height: 160,
              ),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => Level2VideoScreen()),
                );
              },
              style: ElevatedButton.styleFrom(
                primary: Colors.transparent,
                elevation: 0,
              ),
              child: Image.asset(
                'game_assets/btn_level2.png',
                width: 350,
                height: 160,
              ),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => Level3()),
                );
              },
              style: ElevatedButton.styleFrom(
                primary: Colors.transparent,
                elevation: 0,
              ),
              child: Image.asset(
                'game_assets/btn_level3.png',
                width: 350,
                height: 160,
              ),
            ),
            SizedBox(height: 60),
            ElevatedButton(
              onPressed: () {
                Navigator.pushReplacement(
                  context,
                  MaterialPageRoute(builder: (context) => GamesPage()),
                );
              },
              child: Text('Quit Game'),
              style: ElevatedButton.styleFrom(
                primary: Color.fromARGB(255, 231, 65, 43),
                onPrimary: Colors.white,
              ),
            ),
            SizedBox(height: 20),
          ],
        ),
      ),
    );
  }
}

class Level1VideoScreen extends StatefulWidget {
  @override
  _Level1VideoScreenState createState() => _Level1VideoScreenState();
}

class _Level1VideoScreenState extends State<Level1VideoScreen> {
  late VideoPlayerController _controller;
  late ChewieController _chewieController;
  int correctAnswersCount = 0;

  @override
  void initState() {
    super.initState();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]); // Lock orientation to landscape

    _controller = VideoPlayerController.asset('game_assets/EmoX_level1.mp4')
      ..initialize().then((_) {
        setState(() {});
        _controller.play();
      });

    _chewieController = ChewieController(
      videoPlayerController: _controller,
      autoPlay: true,
      looping: false,
      allowMuting: false,
      allowPlaybackSpeedChanging: true,
      allowFullScreen: false,
      showControlsOnInitialize: false,
      customControls: MaterialControls(),
      // Enforcing landscape mode
      aspectRatio: 16 / 9,
      // Setting the orientation to landscape
      deviceOrientationsAfterFullScreen: [
        DeviceOrientation.landscapeLeft,
        DeviceOrientation.landscapeRight,
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Expanded(
            child: Center(
              child: _controller.value.isInitialized
                  ? Chewie(
                      controller: _chewieController,
                    )
                  : CircularProgressIndicator(),
            ),
          ),
          ElevatedButton(
            onPressed: () {
              _controller.pause();
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => HomePage(level: 1),
                ),
              );
            },
            child: Text('Play'),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
    _chewieController.dispose();
  }
}

class Level2VideoScreen extends StatefulWidget {
  @override
  _Level2VideoScreenState createState() => _Level2VideoScreenState();
}

class _Level2VideoScreenState extends State<Level2VideoScreen> {
  late VideoPlayerController _controller;
  late ChewieController _chewieController;
  int correctAnswersCount = 0;

  @override
  void initState() {
    super.initState();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]); // Lock orientation to landscape

    _controller = VideoPlayerController.asset('game_assets/EmoX_level2.mp4')
      ..initialize().then((_) {
        setState(() {});
        _controller.play();
      });

    _chewieController = ChewieController(
      videoPlayerController: _controller,
      autoPlay: true,
      looping: false,
      allowMuting: false,
      allowPlaybackSpeedChanging: true,
      allowFullScreen: false,
      showControlsOnInitialize: false,
      customControls: MaterialControls(),
      // Enforcing landscape mode
      aspectRatio: 16 / 9,
      // Setting the orientation to landscape
      deviceOrientationsAfterFullScreen: [
        DeviceOrientation.landscapeLeft,
        DeviceOrientation.landscapeRight,
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Expanded(
            child: Center(
              child: _controller.value.isInitialized
                  ? Chewie(
                      controller: _chewieController,
                    )
                  : CircularProgressIndicator(),
            ),
          ),
          ElevatedButton(
            onPressed: () {
              _controller.pause();
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => EmotionGame(),
                ),
              );
            },
            child: Text('Play'),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
    _chewieController.dispose();
  }
}

class HomePage extends StatefulWidget {
  final int level;

  HomePage({required this.level});

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  late List<ItemModel> items;
  late List<ItemModel> items2;

  late int score;
  late bool gameOver;

  @override
  void initState() {
    super.initState();
    initGame();
    // Set preferred orientations to portrait mode
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
  }

  initGame() {
    gameOver = false;
    score = 0;
    items = [
      ItemModel(
        name: "Happy",
        value: "happy",
        imagePath: "game_assets/happy.png",
      ),
      ItemModel(
        name: "Sad",
        value: "sad",
        imagePath: "game_assets/sad.png",
      ),
      ItemModel(
        name: "Angry",
        value: "angry",
        imagePath: "game_assets/angry.png",
      ),
      ItemModel(
        name: "Sleepy",
        value: "sleepy",
        imagePath: "game_assets/sleepy.png",
      ),
      ItemModel(
        name: "Surprised",
        value: "surprised",
        imagePath: "game_assets/surprised.png",
      ),
    ];

    items2 = List<ItemModel>.from(items);
    items.shuffle();
    items2.shuffle();
  }

  @override
  Widget build(BuildContext context) {
    if (items.length == 0) gameOver = true;
    return Scaffold(
      backgroundColor: const Color.fromARGB(255, 233, 218, 176),
      appBar: AppBar(
        centerTitle: true,
        title: Text('Mood Matching Game'),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: <Widget>[
            Text.rich(TextSpan(children: [
              TextSpan(text: "Score: "),
              TextSpan(
                  text: "$score",
                  style: TextStyle(
                    color: Colors.green,
                    fontWeight: FontWeight.bold,
                    fontSize: 30.0,
                  ))
            ])),
            if (!gameOver)
              Row(
                children: <Widget>[
                  Column(
                      children: items.map((item) {
                    return Container(
                      margin: const EdgeInsets.all(8.0),
                      child: Draggable<ItemModel>(
                        data: item,
                        childWhenDragging: Image.asset(
                          item.imagePath,
                          width: 90.0,
                          height: 90.0,
                        ),
                        feedback: Image.asset(
                          item.imagePath,
                          width: 90.0,
                          height: 90.0,
                        ),
                        child: Image.asset(
                          item.imagePath,
                          width: 90.0,
                          height: 90.0,
                        ),
                      ),
                    );
                  }).toList()),
                  Spacer(),
                  Column(
                      children: items2.map((item) {
                    return DragTarget<ItemModel>(
                      onAccept: (receivedItem) {
                        if (item.value == receivedItem.value) {
                          setState(() {
                            items.remove(receivedItem);
                            items2.remove(item);
                            score += 10;
                            item.accepting = false;
                          });
                        } else {
                          setState(() {
                            score -= 5;
                            item.accepting = false;
                          });
                        }
                      },
                      onLeave: (receivedItem) {
                        setState(() {
                          item.accepting = false;
                        });
                      },
                      onWillAccept: (receivedItem) {
                        setState(() {
                          item.accepting = true;
                        });
                        return true;
                      },
                      builder: (context, acceptedItems, rejectedItem) =>
                          Container(
                        color: item.accepting ? Colors.red : Colors.teal,
                        height: 50,
                        width: 100,
                        alignment: Alignment.center,
                        margin: const EdgeInsets.all(28.0),
                        child: Text(
                          item.name,
                          style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            fontSize: 18.0,
                          ),
                        ),
                      ),
                    );
                  }).toList()),
                ],
              ),
            if (gameOver)
              Text(
                "Game Over!",
                style: TextStyle(
                  color: const Color.fromARGB(255, 164, 70, 63),
                  fontWeight: FontWeight.bold,
                  fontSize: 24.0,
                ),
              ),
            if (gameOver)
              SizedBox(
                width: double.infinity,
                child: Container(
                  margin:
                      EdgeInsets.only(top: 40.0), // Adjust top margin as needed
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      ElevatedButton(
                        onPressed: () {
                          initGame();
                          setState(() {});
                        },
                        child: Text("New Game"),
                        style: ElevatedButton.styleFrom(
                          primary: Color.fromARGB(255, 22, 167, 42),
                          onPrimary: Colors.white,
                        ),
                      ),
                      SizedBox(
                          height: 10), // Add space between buttons if needed
                      ElevatedButton(
                        onPressed: () {
                          Navigator.pushReplacement(
                            context,
                            MaterialPageRoute(
                              builder: (context) => LevelScreen(),
                            ),
                          );
                        },
                        child: Text("Quit Game"),
                        style: ElevatedButton.styleFrom(
                          primary: Colors.red,
                          onPrimary: Colors.white,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
}

class ItemModel {
  final String name;
  final String value;
  final String imagePath;
  bool accepting;

  ItemModel(
      {required this.name,
      required this.value,
      required this.imagePath,
      this.accepting = false});
}
