import 'package:flutter_riverpod/flutter_riverpod.dart';

/// 路由信息
class RouteInfo {
  final String name;
  final Map<String, String> params;
  const RouteInfo(this.name, {this.params = const {}});

  String param(String key) => params[key] ?? '';
}

/// 路由栈 Notifier
class RouteStackNotifier extends Notifier<List<RouteInfo>> {
  @override
  List<RouteInfo> build() => [const RouteInfo('login')];

  void replace(String name, {Map<String, String> params = const {}}) {
    state = [RouteInfo(name, params: params)];
  }

  void push(String name, {Map<String, String> params = const {}}) {
    state = [...state, RouteInfo(name, params: params)];
  }

  void pop() {
    if (state.length > 1) {
      state = state.sublist(0, state.length - 1);
    }
  }
}

/// 路由栈 Provider
final routeStackProvider =
    NotifierProvider<RouteStackNotifier, List<RouteInfo>>(RouteStackNotifier.new);

/// 当前路由
final currentRouteProvider = Provider<RouteInfo>((ref) {
  final stack = ref.watch(routeStackProvider);
  return stack.last;
});

/// 跳转（替换整个栈）
void goRoute(WidgetRef ref, String name, {Map<String, String> params = const {}}) {
  ref.read(routeStackProvider.notifier).replace(name, params: params);
}

/// 推入新页面
void pushRoute(WidgetRef ref, String name, {Map<String, String> params = const {}}) {
  ref.read(routeStackProvider.notifier).push(name, params: params);
}

/// 返回上一页
void popRoute(WidgetRef ref) {
  ref.read(routeStackProvider.notifier).pop();
}
