import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:frontend/Screens/authentication/login/login_page.dart';
import 'package:frontend/Screens/authentication/loginPage1.dart';
import 'package:frontend/Screens/dashboard/home_page.dart';
import 'package:frontend/Screens/myTemplates/templatesList.dart';
import 'package:frontend/Screens/organization/orgSetup.dart';
import 'package:frontend/Screens/organization/org_List.dart';
import 'package:frontend/Screens/plans/create_plans.dart';
import 'package:frontend/Screens/plans/list_plans.dart';
import 'package:frontend/Screens/policy/policy.dart';
import 'package:frontend/Screens/policy/policy_list.dart';
import 'package:frontend/Screens/userManagement/create_traveller_agent/createTravelAgent.dart';
import 'package:frontend/Screens/userManagement/create_user/create_user1.dart';
import 'package:frontend/Screens/userManagement/user_List.dart';
import 'package:frontend/routes/organizationSetting.dart';
import 'package:go_router/go_router.dart';
import 'package:responsive_builder/responsive_builder.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../Screens/allTrips/list_all_plans.dart';
import '../Screens/allTrips/travel_agent_list.dart';
import '../Screens/approvals/approval_list.dart';
import '../Screens/group/group.dart';
import '../Screens/group/groupList.dart';
import '../Screens/myTemplates/template.dart';
import '../Screens/myTemplates/templateForex.dart';
import '../Screens/myTemplates/templateTest.dart';
import '../Screens/perdiem_amount/forex_list.dart';
import '../Screens/userManagement/create_user/create_user.dart';
import '../Screens/department/department_list.dart';
import '../Screens/purposeOfTravel/purpose_of_travel_list.dart';
import '../Screens/costCenter/costCenter_list.dart';
import '../Screens/dashboard/status_dashboard.dart';
import '../Screens/hotels/hotels_list.dart';
import '../Screens/traveller/travellerList.dart';
import '../Screens/reports/reportList.dart';
import '../Screens/reports/advancePurchase.dart';
import '../Screens/reports/servicesAnalysis.dart';
import '../Screens/reports/misAir.dart';
import '../Screens/reports/misHotel.dart';
import '../Screens/reports/misForex.dart';
import '../Screens/reports/guestHouse.dart';
import '../Screens/userManagement/create_traveller_agent/listTravelAgent.dart';

import '../utils/auth_utils.dart';
import 'mainLayout.dart';

// class AuthState extends ChangeNotifier {
//   String? role;
//
//   Future<void> loadRole() async {
//     final prefs = await SharedPreferences.getInstance();
//     final userData = prefs.getString('user_data');
//     if (userData != null) {
//       final decoded = jsonDecode(userData);
//       role = decoded["role"];
//       notifyListeners();
//     }
//   }
// }
//
// final authState = AuthState();

final GoRouter router = GoRouter(
  // refreshListenable: authState,
  routes: [
    // Public routes without app bar
    GoRoute(path: '/', builder: (context, state) => LoginPage()),

    // Routes that share the app bar and layout (nested routes)
    ShellRoute(
      builder: (context, state, child) {
        // Use ResponsiveBuilder here to detect isDesktop and pass to MainLayout
        return child;
        // return ResponsiveBuilder(
        //   builder: (context, sizingInfo) {
        //     bool isDesktop =
        //         sizingInfo.deviceScreenType == DeviceScreenType.desktop;
        //
        //     return MainLayout(isDesktop: isDesktop, child: child);
        //   },
        // );
      },
      routes: [
        // GoRoute(path: '/home', builder: (context, state) => HomePage()),
        GoRoute(
          path: '/listAllPlan',
          builder: (context, state) => ListAllPlans(),
        ),
        GoRoute(
          path: '/listTravelAgentPlan',
          builder: (context, state) => TravelAgentListPlans(),
        ),
        GoRoute(path: '/listPlan', builder: (context, state) => ListPlans()),
        GoRoute(path: '/createPlan', builder: (context, state) => CreatePlan()),
        GoRoute(
          path: '/allTrips/trips',
          builder: (context, state) => CreatePlan(),
        ),
        GoRoute(
          path: '/approver/plans',
          builder: (context, state) => CreatePlan(),
        ),
        GoRoute(
          path: '/travelagent/trips',
          builder: (context, state) => CreatePlan(),
        ),
        GoRoute(
          path: '/listUser',
          builder: (context, state) => UserListScreen(),
        ),
        GoRoute(
          path: '/CreateUserDetails',
          builder: (context, state) => CreateUserFormDetials(),
        ),
        GoRoute(
          path: '/Policy',
          pageBuilder:
              (context, state) => MaterialPage(child: Policy.fromState(state)),
        ),
        GoRoute(path: '/PolicyList', builder: (context, state) => PolicyList()),
        GoRoute(
          path: '/OrganizationSetup',
          builder: (context, state) => OrgSetUp(),
        ),
        GoRoute(
          path: '/OrganizationSettings',
          builder: (context, state) => OrganizationSetting(),
        ),
        GoRoute(path: '/group', builder: (context, state) => GroupList()),
        GoRoute(
          path: '/getPerdiem',
          builder: (context, state) => ForexDataList(),
        ),
        GoRoute(
          path: '/templateList',
          builder: (context, state) => TemplatesList(),
        ),
        GoRoute(
          path: '/template',
          pageBuilder:
              (context, state) =>
                  MaterialPage(child: Template.fromState(state)),
        ),
        GoRoute(
          path: '/templateForex',
          pageBuilder:
              (context, state) =>
                  MaterialPage(child: TemplateForex.fromState(state)),
        ),
        GoRoute(
          path: '/approvallist',
          builder: (context, state) => ApprovalList(),
        ),
        GoRoute(
          path: '/department',
          builder: (context, state) => DepartmentList(),
        ),
        GoRoute(
          path: '/costcenter',
          builder: (context, state) => CostCenterList(),
        ),
        GoRoute(path: '/hotels', builder: (context, state) => HotelsDataList()),
        GoRoute(
          path: '/statusdashboard',
          builder: (context, state) => StatusDashboard(),
        ),
        GoRoute(
          path: '/unauthorized',
          builder:
              (context, state) =>
                  const Scaffold(body: Center(child: Text("🚫 Access Denied"))),
        ),

        GoRoute(
          path: '/traveller',
          builder: (context, state) => TravellerList(),
        ),
        GoRoute(
          path: '/CreateGroup',
          pageBuilder:
              (context, state) => MaterialPage(child: Group.fromState(state)),
        ),
        GoRoute(path: '/report', builder: (context, state) => ReportList()),
        GoRoute(
          path: '/advancePurchase',
          builder: (context, state) => AdvancePurchase(),
        ),
        GoRoute(
          path: '/misservicesAnalysis',
          builder: (context, state) => ServicesAnalysis(),
        ),
        GoRoute(path: '/misAirReport', builder: (context, state) => MISair()),
        GoRoute(
          path: '/misHotelReport',
          builder: (context, state) => MIShotel(),
        ),
        GoRoute(
          path: '/misForexReport',
          builder: (context, state) => MISforex(),
        ),
        GoRoute(
          path: '/guestHouseReport',
          builder: (context, state) => GuestHouse(),
        ),
        GoRoute(
          path: '/listTravelAgent',
          builder: (context, state) => TravelAgentListScreen(),
        ),
        GoRoute(
          path: '/CreateTravelAgent',
          builder: (context, state) => CreateTravelAgentFormDetials(),
        ),
        GoRoute(
          path: '/PurposeOfTravel',
          builder: (context, state) => PurposeOfTravelList(),
        ),
      ],
    ),
  ],

  // redirect: (context, state) async {
  //   print('Check REDIRECTION');
  //   final apiStatus = ApiStatusCache.latestStatus;
  //
  //   print('Check apiStatus - $apiStatus');
  //   return null;
  // if (apiStatus == 404) return '/';
  // return null;

  // final role = await getRoleUser(); // async not allowed here per-route
  // print('Check REDIRECTION');
  // print('getRoleUser1 - $role');
  // // for top-level GoRouter, you can use async redirect
  // if (role == null) return '/'; // not logged in
  // if (state.matchedLocation == '/statusdashboard' &&
  //     role != 'Org Admin' &&
  //     role != 'Travel Admin') {
  //   return '/unauthorized';
  // }
  // return null; //
  // },
);

class ApiStatusCache {
  static int? latestStatus;
}
