import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:rasadyar_core/core.dart';

import 'logic.dart';

class RootPage extends GetView<RootLogic> {
  RootPage({super.key});

  // Extracted back-press
  Future<void> _handleBackPress(BuildContext context) async {
    final nestedKey = Get.nestedKey(controller.currentIndex.value);
    final currentNavigator = nestedKey?.currentState;
    if (currentNavigator?.canPop() ?? false) {
      currentNavigator?.pop();
      return;
    }
    final now = DateTime.now();
    /*if (controller.lastBackPressed == null ||
        now.difference(controller.lastBackPressed!) > const Duration(seconds: 2)) {
      controller.lastBackPressed = now;
      Get.snackbar(
        'خروج از برنامه',
        'برای خروج دوباره بازگشت را بزنید',
        snackPosition: SnackPosition.TOP,
        duration: const Duration(seconds: 2),
        backgroundColor: AppColor.warning,
      );
    } else {
      await SystemNavigator.pop();
    }*/
  }

  @override
  Widget build(BuildContext context) {
    return ObxValue((currentIndex) {
      return PopScope(
        canPop: false,
        onPopInvokedWithResult: (didPop, result) async {
          await _handleBackPress(context);
        },
        child: Scaffold(
          body: IndexedStack(
            children: controller.pages,
            index: currentIndex.value,
            sizing: StackFit.expand,
          ),
          bottomNavigationBar: RBottomNavigation(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            items: [
              RBottomNavigationItem(
                label: 'نقشه',
                icon: Assets.vec.mapSvg.path,
                isSelected: currentIndex.value == 0,
                onTap: () {
                  Get.nestedKey(1)?.currentState?.popUntil((route) => route.isFirst);
                  controller.changePage(0);
                },
              ),
              RBottomNavigationItem(
                label: 'درخواست‌ها',
                icon: Assets.vec.settingSvg.path,
                isSelected: currentIndex.value == 1,
                onTap: () {
                  Get.nestedKey(0)?.currentState?.popUntil((route) => route.isFirst);
                  controller.changePage(1);
                },
              ),
              RBottomNavigationItem(
                label: 'پروفایل',
                icon: Assets.vec.profileCircleSvg.path,
                isSelected: currentIndex.value == 2,
                onTap: () {
                  Get.nestedKey(1)?.currentState?.popUntil((route) => route.isFirst);
                  Get.nestedKey(0)?.currentState?.popUntil((route) => route.isFirst);

                  controller.changePage(2);
                },
              ),
            ],
          ),
        ),
      );
    }, controller.currentIndex);
  }
}
