// needed for web horizontal scroll behavior
import 'package:flutter/material.dart';
import 'package:fotodocumentation/main.dart';
import 'package:fotodocumentation/pages/customer/customer_list_widget.dart';
import 'package:fotodocumentation/pages/customer/customer_widget.dart';
import 'package:fotodocumentation/pages/login/login_widget.dart';
import 'package:fotodocumentation/utils/di_container.dart';
import 'package:fotodocumentation/utils/login_credentials.dart';
import 'package:go_router/go_router.dart';

class GlobalRouter {
  static final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root');
  static final GlobalKey<NavigatorState> bottomBarNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'bottombar');
  static final GlobalKey<NavigatorState> adminNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'admin');
  static final GlobalKey<NavigatorState> skillEditorNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'skillEditor');

  static final String pathHome = "/home";
  static final String pathCustomer = "/customer";
  static final String pathLogin = "/login";

  static final GoRouter router = createRouter(pathHome);

  static GoRouter createRouter(String initialLocation) {
    return GoRouter(
      navigatorKey: rootNavigatorKey,
      initialLocation: initialLocation,
      routes: <RouteBase>[
        GoRoute(
          path: "/",
          redirect: (_, __) => pathHome,
        ),
        GoRoute(
          path: pathLogin,
          builder: (BuildContext context, GoRouterState state) => const LoginWidget(),
        ),
        GoRoute(
          path: pathHome,
          builder: (context, state) => CustomerListWidget(),
        ),
        GoRoute(
          path: "$pathCustomer/:id",
          builder: (context, state) {
            var idStr = state.pathParameters['id'];
            var id = idStr == null ? null : int.tryParse(idStr);
            return CustomerWidget(customerId: id ?? -1);
          },
        ),
      ],
      redirect: (context, state) {
        var uriStr = state.uri.toString();
        logger.t("uri $uriStr");
        LoginCredentials loginCredentials = DiContainer.get();

        if (!loginCredentials.isLoggedIn) {
          return pathLogin;
        }
        return null;
      },
    );
  }
}
