import 'package:autosos_flutter/pages/home/home_page.dart';
import 'package:autosos_flutter/pages/login/login_page.dart';
import 'package:autosos_flutter/pages/login/bind_phone_page.dart';
import 'package:autosos_flutter/pages/login/bind_wx_page.dart';
import 'package:autosos_flutter/pages/me/me_page.dart';
import 'package:autosos_flutter/pages/me/authentication_page.dart';
import 'package:autosos_flutter/pages/me/perfect_page.dart';
import 'package:autosos_flutter/pages/me/withdrawal_page.dart';
import 'package:autosos_flutter/pages/me/withdrawal_record_page.dart';
import 'package:autosos_flutter/pages/me/recharge_page.dart';
import 'package:autosos_flutter/pages/me/amount_list_page.dart';
import 'package:autosos_flutter/pages/me/feedback_page.dart';
import 'package:autosos_flutter/pages/me/messenger_page.dart';
import 'package:autosos_flutter/pages/me/setting_page.dart';
import 'package:autosos_flutter/pages/me/optimization_page.dart';
import 'package:autosos_flutter/pages/order/check_page.dart';
import 'package:autosos_flutter/pages/order/waiting_page.dart';
import 'package:autosos_flutter/pages/order/conduct_page.dart';
import 'package:autosos_flutter/pages/order/photograph_page.dart';
import 'package:autosos_flutter/pages/order/autograph_page.dart';
import 'package:autosos_flutter/pages/order/collection_page.dart';
import 'package:autosos_flutter/pages/order/complete_page.dart';
import 'package:autosos_flutter/pages/order/record_page.dart';
import 'package:autosos_flutter/pages/splash/splash_page.dart';
import 'package:autosos_flutter/pages/welcome/welcome_page.dart';
import 'package:autosos_flutter/pages/webview/agent_web_page.dart';
import 'package:autosos_flutter/pages/common/qr_scan_page.dart';
import 'package:autosos_flutter/provider/providers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';

/// 路由名集中定义
class Routes {
  static const splash = '/';
  static const welcome = '/welcome';
  static const login = '/login';
  static const bindPhone = '/bind-phone';
  static const bindWx = '/bind-wx';

  static const home = '/home';
  static const me = '/me';
  static const perfect = '/me/perfect';
  static const auth = '/me/auth';
  static const withdrawal = '/me/withdrawal';
  static const withdrawalRecord = '/me/withdrawal/record';
  static const recharge = '/me/recharge';
  static const amountList = '/me/amount';
  static const feedback = '/me/feedback';
  static const messenger = '/me/messenger';
  static const setting = '/me/setting';
  static const optimization = '/me/optimization';

  static const orderCheck = '/order/check';
  static const orderWaiting = '/order/waiting';
  static const orderConduct = '/order/conduct';
  static const orderPhotograph = '/order/photograph';
  static const orderAutograph = '/order/autograph';
  static const orderCollection = '/order/collection';
  static const orderComplete = '/order/complete';
  static const orderRecord = '/order/record';

  static const webview = '/webview';
  static const qrScan = '/qr-scan';
}

final routerProvider = Provider<GoRouter>((ref) {
  return GoRouter(
    initialLocation: Routes.splash,
    redirect: (context, state) {
      final logged = ref.read(isLoggedInProvider);
      final loc = state.matchedLocation;
      final isAuthRoute = loc == Routes.login || loc == Routes.bindPhone || loc == Routes.bindWx;

      // 未登录 → 跳登录
      if (!logged && !isAuthRoute && loc != Routes.splash && loc != Routes.welcome) {
        return Routes.login;
      }
      // 已登录 → 不能留在登录页
      if (logged && isAuthRoute) {
        return Routes.home;
      }
      return null;
    },
    refreshListenable: _AuthListenable(ref),
    routes: [
      GoRoute(path: Routes.splash, builder: (_, __) => const SplashPage()),
      GoRoute(path: Routes.welcome, builder: (_, __) => const WelcomePage()),
      GoRoute(path: Routes.login, builder: (_, __) => const LoginPage()),
      GoRoute(path: Routes.bindPhone, builder: (_, __) => const BindPhonePage()),
      GoRoute(path: Routes.bindWx, builder: (_, __) => const BindWxPage()),

      GoRoute(path: Routes.home, builder: (_, __) => const HomePage()),
      GoRoute(path: Routes.me, builder: (_, __) => const MePage()),
      GoRoute(path: Routes.perfect, builder: (_, __) => const PerfectPage()),
      GoRoute(path: Routes.auth, builder: (_, __) => const AuthenticationPage()),
      GoRoute(path: Routes.withdrawal, builder: (_, __) => const WithdrawalPage()),
      GoRoute(path: Routes.withdrawalRecord, builder: (_, __) => const WithdrawalRecordPage()),
      GoRoute(path: Routes.recharge, builder: (_, __) => const RechargePage()),
      GoRoute(path: Routes.amountList, builder: (_, __) => const AmountListPage()),
      GoRoute(path: Routes.feedback, builder: (_, __) => const FeedbackPage()),
      GoRoute(path: Routes.messenger, builder: (_, __) => const MessengerPage()),
      GoRoute(path: Routes.setting, builder: (_, __) => const SettingPage()),
      GoRoute(path: Routes.optimization, builder: (_, __) => const OptimizationPage()),

      GoRoute(path: Routes.orderCheck, builder: (_, __) => const CheckPage()),
      GoRoute(path: Routes.orderWaiting, builder: (_, __) => const WaitingPage()),
      GoRoute(
        path: '${Routes.orderConduct}/:id',
        builder: (_, s) => ConductPage(orderId: int.parse(s.pathParameters['id']!)),
      ),
      GoRoute(
        path: '${Routes.orderPhotograph}/:id',
        builder: (_, s) => PhotographPage(orderId: int.parse(s.pathParameters['id']!)),
      ),
      GoRoute(
        path: '${Routes.orderAutograph}/:id',
        builder: (_, s) => AutographPage(orderId: int.parse(s.pathParameters['id']!)),
      ),
      GoRoute(
        path: '${Routes.orderCollection}/:id',
        builder: (_, s) => CollectionPage(orderId: int.parse(s.pathParameters['id']!)),
      ),
      GoRoute(
        path: '${Routes.orderComplete}/:id',
        builder: (_, s) => CompletePage(orderId: int.parse(s.pathParameters['id']!)),
      ),
      GoRoute(path: Routes.orderRecord, builder: (_, __) => const OrderRecordPage()),

      GoRoute(
        path: Routes.webview,
        builder: (_, s) => AgentWebPage(
          url: s.uri.queryParameters['url'] ?? '',
          title: s.uri.queryParameters['title'] ?? '',
        ),
      ),
      GoRoute(path: Routes.qrScan, builder: (_, __) => const QrScanPage()),
    ],
  );
});

/// 把 token 变更同步给 GoRouter 触发 redirect
class _AuthListenable extends ChangeNotifier {
  _AuthListenable(this.ref) {
    ref.listen<String?>(accessTokenProvider, (_, __) => notifyListeners());
  }
  final Ref ref;
}