// home_screen.dart
import 'package:flutter/material.dart';
import 'package:game_miniapp/game_miniapp.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/preference/data_preference.dart';
import 'package:mypoint_flutter_app/shared/router_gage.dart';
import '../setting/setting_screen.dart';

class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ElevatedButton(onPressed: () => _showMiniGame(context), child: const Text('Mini Game')),
            ElevatedButton(onPressed: () => _logout(context), child: const Text('Đăng xuất')),
            ElevatedButton(onPressed: () => _showSetting(context), child: const Text('Setting')),
            ElevatedButton(onPressed: () => _showNotify(context), child: const Text('Notify')),
          ],
        ),
      ),
    );
  }

  void _showNotify(BuildContext context) async {
    Get.toNamed(notificationScreen);
  }

  void _showMiniGame(BuildContext context) async {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (_) => const GameMiniAppScreen()),
    );
  }

  void _logout(BuildContext context) async {
    final confirm = await showDialog<bool>(
      context: context,
      builder:
          (ctx) => AlertDialog(
            title: const Text('Xác nhận'),
            content: const Text('Bạn có chắc muốn đăng xuất?'),
            actions: [
              TextButton(onPressed: () => Navigator.of(ctx).pop(false), child: const Text('Hủy')),
              TextButton(onPressed: () => Navigator.of(ctx).pop(true), child: const Text('Đăng xuất')),
            ],
          ),
    );

    if (confirm == true) {
      DataPreference.instance.clearLoginToken();
      _safeBackToLogin();
      // Get.until((route) => route.settings.name == loginScreen);
    }
  }

  void _safeBackToLogin() {
    bool found = false;
    Navigator.popUntil(Get.context!, (route) {
      final matched = route.settings.name == loginScreen;
      if (matched) found = true;
      return matched;
    });
    final phone = DataPreference.instance.phone;
    if (phone != null) {
      if (!found) {
        Get.offAllNamed(loginScreen, arguments: phone);
      }
    } else {
      DataPreference.instance.clearData();
      Get.offAllNamed(onboardingScreen);
    }
  }

  void _showSetting(BuildContext context) async {
    Get.toNamed(settingScreen);
  }
}