import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:nhance_partner/core/routing/routes.dart';
import 'package:nhance_partner/presentation/screens/Enquiry/enquiryList.dart';
import 'package:nhance_partner/presentation/screens/Masters/PaymentMode/paymentList.dart';
import 'package:nhance_partner/presentation/screens/UserManagement/Profile/profile_web.dart';
import 'package:nhance_partner/presentation/screens/dashboard/dashboard_nw.dart';
import 'package:nhance_partner/presentation/screens/payout/invoice_list.dart';

import '../../data/services/auth_service.dart';
import '../../presentation/providers/manager_provider.dart';
import '../../presentation/screens/Enquiry/enquiry/tabs.dart';
import '../../presentation/screens/Enquiry/policy_claims_endros/claims.dart';
import '../../presentation/screens/Enquiry/policy_claims_endros/endorsomentUpdateValidation.dart';
import '../../presentation/screens/Enquiry/policy_claims_endros/endrosment.dart';
import '../../presentation/screens/Masters/Brokers/brokerList.dart';
import '../../presentation/screens/Masters/EndorsementType/endorsementList.dart';
import '../../presentation/screens/Masters/VehicleType/vehicleList.dart';
import '../../presentation/screens/StaffAttendance/attendanceAllDetails.dart';
import '../../presentation/screens/StaffAttendance/individual_Attendance.dart';
import '../../presentation/screens/UserManagement/Agent/agent.dart';
import '../../presentation/screens/UserManagement/Agent/agentList.dart';
import '../../presentation/screens/UserManagement/POS/pos_list.dart';
import '../../presentation/screens/UserManagement/Profile/profile_mobile.dart';
import '../../presentation/screens/UserManagement/SalesExecutive/salesExecutive.dart';
import '../../presentation/screens/UserManagement/SalesExecutive/salesExecutiveList.dart';
import '../../presentation/screens/UserManagement/Staff/staff.dart';
import '../../presentation/screens/UserManagement/Staff/staffList.dart';
import '../../presentation/screens/dashboard/dashboard.dart';
import '../../presentation/screens/handler/enquiryList.dart';
import '../../presentation/screens/handler/enquiryListOld.dart';
import '../../presentation/screens/home/home_screen.dart';
import '../../presentation/screens/login/login_screen.dart';
import '../../presentation/screens/payout/payout_screen.dart';
import '../../presentation/screens/splash/splash_screen.dart';
import '../../presentation/screens/staff/Enquiry/enquiry_inline_Edit_17Nov.dart';
import '../../presentation/screens/staff/Enquiry/enquiry_inline_list.dart';
import '../../presentation/screens/staff/Enquiry/enquiry_list.dart';
import '../../presentation/screens/staff/Enquiry/staff_policy.dart';
import '../../presentation/screens/staff/policy/policy.dart';
import '../../presentation/screens/staff/policy/policy_list.dart';
import '../../presentation/screens/staff/policy/policy_validation.dart';
import '../../presentation/screens/staff/quotations/quotation.dart';
import '../config/navigation_service.dart';

final GoRouter appRouter = GoRouter(
  navigatorKey: navigatorKey,
  initialLocation: AppRoutes.login,
  // initialLocation: AppRoutes.home,
  routes: [
    GoRoute(
      path: AppRoutes.splash,
      builder: (context, state) => const SplashScreen(),
    ),
    GoRoute(
      path: AppRoutes.login,
      builder: (context, state) => const LoginScreen(),
    ),
    // GoRoute(
    //   path: AppRoutes.home,
    //   builder: (context, state) => const HomeScreen(),
    // ),
    GoRoute(
      path: AppRoutes.dashboard,
      // builder: (context, state) => const DashboardScreen(),
      builder: (context, state) => const Dashboard(),
    ),

    GoRoute(
      path: AppRoutes.payout,
      builder: (context, state) {
        final editItem = state.extra as Map<String, dynamic>?;
        return PayOutScreen(editItem: editItem);
      },
    ),

    GoRoute(
      path: AppRoutes.invoiceList,
      builder: (context, state) => const InvoiceList(),
    ),

    GoRoute(
      path: AppRoutes.profile,
      builder: (context, state) => const Profile(),
    ),

    GoRoute(
      path: AppRoutes.agentLst,
      // builder: (context, state) => const Agent(),
      builder: (context, state) => const AgentList(),
    ),

    // GoRoute(
    //   path: '/agent/:id',
    //   builder: (context, state) {
    //     final id = state.pathParameters['id']!;
    //
    //     // if "create", open empty form
    //     if (id == 'create') {
    //       return const Agent(); // create mode
    //     } else {
    //       return Agent(id: id); // update mode
    //     }
    //   },
    // ),
    GoRoute(
      path: AppRoutes.staffLst,
      // builder: (context, state) => const Agent(),
      builder: (context, state) => const StaffList(),
    ),

    // GoRoute(
    //   path: '/staff/:id',
    //   builder: (context, state) {
    //     final id = state.pathParameters['id']!;
    //     // if "create", open empty form
    //     if (id == 'create') {
    //       return const Staff(); // create mode
    //     } else {
    //       return Staff(id: id); // update mode
    //     }
    //   },
    // ),
    GoRoute(
      path: AppRoutes.posLst,
      // builder: (context, state) => const Agent(),
      builder: (context, state) => const PosList(),
    ),

    GoRoute(
      path: AppRoutes.salesExecutiveLst,
      // builder: (context, state) => const Agent(),
      builder: (context, state) => const SalesExecutiveList(),
    ),

    // GoRoute(
    //   path: '/salesExecutive/:id',
    //   builder: (context, state) {
    //     final id = state.pathParameters['id']!;
    //     // if "create", open empty form
    //     if (id == 'create') {
    //       return const SalesExecutive(); // create mode
    //     } else {
    //       return SalesExecutive(id: id); // update mode
    //     }
    //   },
    // ),
    GoRoute(
      path: AppRoutes.enquiryLst,
      builder: (context, state) => const EnquiryList(),
    ),

    // GoRoute(
    //   path: '/tabEnquiry/:id',
    //   builder: (context, state) {
    //     final id = state.pathParameters['id']!;
    //     // if "create", open empty form
    //     if (id == 'tab') {
    //       return TabEnquiryList(); // create mode
    //     } else {
    //       return TabEnquiryList(id: id); // update mode
    //     }
    //   },
    // ),
    GoRoute(
      path: AppRoutes.tabEnquiry,
      builder: (context, state) {
        return TabEnquiryList(); // no id in path
      },
    ),

    // GoRoute(
    //   path: AppRoutes.tabEnquiry,
    //   builder: (context, state) {
    //     return Consumer(
    //       builder: (context, ref, _) {
    //         final id = state.pathParameters['id']!;
    //         ref.read(enquiryIdProvider.notifier).state = (id == 'tab')
    //             ? null
    //             : id;
    //         return TabEnquiryList();
    //       },
    //     );
    //   },
    // ),
    GoRoute(
      path: AppRoutes.claimlist,
      builder: (context, state) => const claimList(),
    ),
    GoRoute(
      path: AppRoutes.Endorsement,
      builder: (context, state) => const Endorsement(),
    ),
    GoRoute(
      path: AppRoutes.policylist,
      builder: (context, state) => const policylist(),
    ),
    GoRoute(
      path: AppRoutes.policyValidation,
      name: "policyValidation",
      pageBuilder: (context, state) {
        final item = state.extra;

        return CustomTransitionPage(
          key: state.pageKey,
          opaque: true, // ⭐ required for open animation
          barrierColor: Colors.black.withOpacity(
            0.3,
          ), // optional dim background
          fullscreenDialog: true,

          transitionDuration: const Duration(milliseconds: 1000),

          child: policyValidation(item: item),

          transitionsBuilder: (context, animation, secondaryAnimation, child) {
            final curved = CurvedAnimation(
              parent: animation,
              curve: Curves.easeOutCubic,
            );

            return SlideTransition(
              position: Tween<Offset>(
                begin: const Offset(0, 1), // slide from bottom
                end: Offset.zero,
              ).animate(curved),
              child: child,
            );
          },
        );
      },
    ),

    GoRoute(
      path: AppRoutes.endorsomentValidation,
      name: "endorsomentValidation",
      pageBuilder: (context, state) {

        final extra = state.extra as Map<String, dynamic>;

        return CustomTransitionPage(
          key: state.pageKey,
          opaque: true,
          barrierColor: Colors.black.withOpacity(0.3),
          fullscreenDialog: true,
          transitionDuration: const Duration(milliseconds: 1000),

          child: endorsomentValidation(
            title: extra["title"],
            userId: extra["userId"],
            managerId: extra["managerId"],
            role: extra["role"],
            item: extra["item"],
            onSubmit: (value) {
              debugPrint("Validation Done: $value");
            },
          ),

          transitionsBuilder: (context, animation, secondaryAnimation, child) {
            final curved = CurvedAnimation(
              parent: animation,
              curve: Curves.easeOutCubic,
            );

            return SlideTransition(
              position: Tween<Offset>(
                begin: const Offset(0, 1),
                end: Offset.zero,
              ).animate(curved),
              child: child,
            );
          },
        );
      },
    ),

    GoRoute(
      path: AppRoutes.quotation,
      builder: (context, state) => const QuotationScreen(),
    ),
    GoRoute(
      path: AppRoutes.policy,
      builder: (context, state) => const PolicyScreen(),
    ),
    GoRoute(
      path: AppRoutes.policy,
      builder: (context, state) => const PolicyScreen(),
    ),

    GoRoute(
      path: AppRoutes.policyStaffEnq,
      builder: (context, state) => PolicyStaffEnqList(),
    ),

  GoRoute(
      path: AppRoutes.enquiryForStaff,
      builder: (context, state) => const EnquiryListStaffInline(),
      // builder: (context, state) => const EnquiryListStaffInlineTST(),

      // builder: (context, state) => const EnquiryStaff(),
    ),
    GoRoute(
      path: AppRoutes.enquiryHandlerLst,
      // builder: (context, state) => const EnquiryHandler(),
      builder: (context, state) => EnquiryListHandler(),
    ),
    GoRoute(
      path: AppRoutes.allStaffAttendance,
      builder: (context, state) => const AttendanceAllDetails(),
    ),

    GoRoute(
      path: AppRoutes.individualAttendance,
      builder: (context, state) => const IndividualAttendanceDetails(),
    ),

    GoRoute(
      path: AppRoutes.brokerLst,
      builder: (context, state) => const BrokerList(),
    ),
    GoRoute(
      path: AppRoutes.endorsementTypeLst,
      builder: (context, state) => const EndorsementTypeList(),
    ),
    GoRoute(
      path: AppRoutes.vehicleTypeLst,
      builder: (context, state) => const VehicleTypeList(),
    ),
    GoRoute(
      path: AppRoutes.paymentModeLst,
      builder: (context, state) => const PaymentLsit(),
    ),
  ],
  redirect: (context, state) async {
    final loggedIn = await AuthService.isLoggedIn();
    // final goingToLogin = state.matchedLocation == AppRoutes.login;

    final currentLocation = state.matchedLocation;
    final goingToLogin = currentLocation.startsWith(AppRoutes.login);
    print("loggedIn - $loggedIn");
    print("currentLocation - $currentLocation");
    print("goingToLogin - $goingToLogin");

    if (!loggedIn) {
      // Not logged in → redirect to login with "next" param
      if (!goingToLogin) {
        return '${AppRoutes.login}?next=$currentLocation';
      }
      return null; // already on login → stay
    }

    if (loggedIn && goingToLogin) {
      // Logged in but going to login → send to "next" if present
      final next = state.uri.queryParameters['next'];
      return next ?? AppRoutes.login;
    }

    // if (!loggedIn && !goingToLogin) return AppRoutes.login;
    // if (loggedIn && goingToLogin) return AppRoutes.home;

    return null; // stay on current route
  },
);
