import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:go_router/go_router.dart';

import '../../features/approvals/history/presentation/pages/approval_history_page.dart';
import '../../features/auth/application/auth_service.dart';
import '../../features/approvals/request/presentation/pages/approval_request_page.dart';
import '../../features/approvals/step/presentation/pages/approval_step_page.dart';
import '../../features/approvals/template/presentation/pages/approval_template_page.dart';
import '../../features/dashboard/presentation/pages/dashboard_page.dart';
import '../../features/inventory/inbound/presentation/pages/inbound_page.dart';
import '../../features/inventory/outbound/presentation/pages/outbound_page.dart';
import '../../features/inventory/rental/presentation/pages/rental_page.dart';
import '../../features/inventory/summary/presentation/pages/inventory_summary_page.dart';
import '../../features/login/presentation/pages/login_page.dart';
import '../../features/masters/customer/presentation/pages/customer_page.dart';
import '../../features/masters/group/presentation/pages/group_page.dart';
import '../../features/masters/group_permission/presentation/pages/group_permission_page.dart';
import '../../features/masters/menu/presentation/pages/menu_page.dart';
import '../../features/masters/product/presentation/pages/product_page.dart';
import '../../features/masters/user/presentation/pages/user_page.dart';
import '../../features/masters/vendor/presentation/pages/vendor_page.dart';
import '../../features/masters/warehouse/presentation/pages/warehouse_page.dart';
import '../../features/reporting/presentation/pages/reporting_page.dart';
import '../../features/util/postal_search/presentation/pages/postal_search_page.dart';
import '../../widgets/app_shell.dart';
import '../constants/app_sections.dart';
import '../permissions/permission_manager.dart';
import '../permissions/permission_resources.dart';
import 'auth_guard.dart';

/// 전역 네비게이터 키(로그인/셸 라우터 공용).
final _rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root');

/// 애플리케이션 전체 라우팅 구성을 담당하는 GoRouter 인스턴스.
///
/// - 로그인 전용 라우트는 루트(primary) 네비게이터에서 처리한다.
/// - 로그인 이후 화면은 [ShellRoute] 하위에서 `AppShell` 레이아웃을 공유한다.
/// - 각 기능 모듈은 고유 name/path를 가지며 `GoRouter` 딥링크와 연결된다.
final appRouter = GoRouter(
  navigatorKey: _rootNavigatorKey,
  initialLocation: loginRoutePath,
  redirect: (context, state) {
    final authService = GetIt.I<AuthService>();
    final loggedIn = authService.session != null;
    final loggingIn = state.uri.path == loginRoutePath;
    if (!loggedIn && !loggingIn) {
      return loginRoutePath;
    }
    if (loggedIn && loggingIn) {
      return dashboardRoutePath;
    }
    return null;
  },
  routes: [
    GoRoute(path: '/', redirect: (_, __) => loginRoutePath),
    GoRoute(
      path: loginRoutePath,
      name: 'login',
      builder: (context, state) => const LoginPage(),
    ),
    ShellRoute(
      builder: (context, state, child) =>
          AppShell(currentLocation: state.uri.toString(), child: child),
      routes: [
        GoRoute(
          path: dashboardRoutePath,
          name: 'dashboard',
          builder: (context, state) => const DashboardPage(),
        ),
        GoRoute(
          path: inventorySummaryRoutePath,
          name: 'inventory-summary',
          redirect: (context, state) {
            if (!AuthGuard.can(inventorySummaryRoutePath)) {
              return dashboardRoutePath;
            }
            if (!AuthGuard.can(PermissionResources.inventoryScope)) {
              return dashboardRoutePath;
            }
            return null;
          },
          builder: (context, state) =>
              InventorySummaryPage(routeUri: state.uri),
        ),
        GoRoute(
          path: '/inventory/inbound',
          name: 'inventory-inbound',
          builder: (context, state) => InboundPage(routeUri: state.uri),
        ),
        GoRoute(
          path: '/inventory/outbound',
          name: 'inventory-outbound',
          builder: (context, state) => OutboundPage(routeUri: state.uri),
        ),
        GoRoute(
          path: '/inventory/rental',
          name: 'inventory-rental',
          builder: (context, state) => RentalPage(routeUri: state.uri),
        ),
        GoRoute(
          path: '/masters/vendors',
          name: 'masters-vendors',
          builder: (context, state) => VendorPage(routeUri: state.uri),
        ),
        GoRoute(
          path: '/masters/products',
          name: 'masters-products',
          builder: (context, state) => ProductPage(routeUri: state.uri),
        ),
        GoRoute(
          path: '/masters/warehouses',
          name: 'masters-warehouses',
          builder: (context, state) => WarehousePage(routeUri: state.uri),
        ),
        GoRoute(
          path: '/masters/customers',
          name: 'masters-customers',
          builder: (context, state) => CustomerPage(routeUri: state.uri),
        ),
        GoRoute(
          path: '/masters/users',
          name: 'masters-users',
          builder: (context, state) => const UserPage(),
        ),
        GoRoute(
          path: '/masters/groups',
          name: 'masters-groups',
          builder: (context, state) => const GroupPage(),
        ),
        GoRoute(
          path: '/masters/menus',
          name: 'masters-menus',
          builder: (context, state) => const MenuPage(),
        ),
        GoRoute(
          path: '/masters/group-permissions',
          name: 'masters-group-permissions',
          builder: (context, state) => const GroupPermissionPage(),
        ),
        GoRoute(
          path: '/approvals/requests',
          name: 'approvals-requests',
          redirect: AuthGuard.require(
            resource: '/approvals/requests',
            action: PermissionAction.view,
            fallback: dashboardRoutePath,
          ),
          builder: (context, state) => ApprovalRequestPage(routeUri: state.uri),
        ),
        GoRoute(
          path: '/approvals/steps',
          name: 'approvals-steps',
          redirect: AuthGuard.require(
            resource: '/approvals/steps',
            action: PermissionAction.view,
            fallback: dashboardRoutePath,
          ),
          builder: (context, state) => const ApprovalStepPage(),
        ),
        GoRoute(
          path: '/approvals/history',
          name: 'approvals-history',
          redirect: AuthGuard.require(
            resource: '/approvals/history',
            action: PermissionAction.view,
            fallback: dashboardRoutePath,
          ),
          builder: (context, state) => const ApprovalHistoryPage(),
        ),
        GoRoute(
          path: '/approvals/templates',
          name: 'approvals-templates',
          redirect: AuthGuard.require(
            resource: '/approvals/templates',
            action: PermissionAction.view,
            fallback: dashboardRoutePath,
          ),
          builder: (context, state) => const ApprovalTemplatePage(),
        ),
        GoRoute(
          path: '/utilities/postal-search',
          name: 'utilities-postal-search',
          builder: (context, state) => const PostalSearchPage(),
        ),
        GoRoute(
          path: '/reports',
          name: 'reports',
          builder: (context, state) => const ReportingPage(),
        ),
      ],
    ),
  ],
);
