import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:jiffy/jiffy.dart';
import 'package:tp5/authpages/auth_magiclink.dart';
import 'package:tp5/authpages/login_otp.dart';
import 'package:tp5/core/basic_page.dart';
import 'package:tp5/core/utils.dart';
import 'package:tp5/flightslist/flightslist_page.dart';
import 'package:tp5/fltinfo/view/dutyinfo_page.dart';
import 'package:tp5/fltinfo/view/fltinfo_page.dart';
import 'package:tp5/ftl/view/ftl_page.dart';
import 'package:tp5/lido/view/lido_form.dart';
import 'package:tp5/lido/view/lidolist_page.dart';
import 'package:tp5/lido/view/lidoofp_page.dart';
import 'package:tp5/onboarding/onboarding.dart';
import 'package:tp5/pdf/pdf_page.dart';
import 'package:tp5/roster/view/crewlink_form.dart';
import 'package:tp5/roster/view/crewlist_page.dart';
import 'package:tp5/roster/view/roster_page.dart';
import 'package:tp5/rosters/rosters_page.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import 'package:tp5/settings/settings_page.dart';
import 'package:tp5/widgets/nav_drawer.dart';

final routeProvider = Provider<RouterConfig<Object>?>((ref) {
  return _routes;
});

final _routes = GoRouter(
  debugLogDiagnostics: false,
  redirect: (context, state) {
    log("${state.fullPath} | ${state.extra.runtimeType.toString()}",
        name: "routes");

    // Check app expiration
    if (DateTime.now().isAfter(DateTime(2024, 12, 31))) {
      return "/expired";
    }

    // Get current auth state
    final session = Supabase.instance.client.auth.currentSession;
    final isLoggedIn = session != null;

    // List of paths that don't require authentication
    final publicPaths = ['/auth/login-otp', '/magic-link', '/auth/signup'];
    final isPublicPath = publicPaths.contains(state.fullPath);

    // Redirect to login if not authenticated and trying to access protected route
    if (!isLoggedIn && !isPublicPath) {
      return '/auth/login-otp';
    }

    // Allow access to public paths even when logged out
    if (isPublicPath) {
      return null;
    }

    return null;
  },
  //  initialLocation: '/test',
  // initialLocation: '/auth/magiclink',
  initialLocation: '/home',
  routes: [
    GoRoute(
        path: '/magic-link',
        builder: (BuildContext context, GoRouterState state) {
          // Access query parameters here
          final token = state.uri.queryParameters['token'];
          return AuthMagiclink(token: token);
        }),
    GoRoute(
      path: '/test',
      builder: (context, state) => Text("test"),
    ),
    GoRoute(
        path: "/auth",
        redirect: (_, state) {
          // if
          //     (state.fullPath != "/crewlink/settings" &&
          //         (((Hive.box("settings").get("crewlink_user") ?? "") == "") ||
          //             ((Hive.box("settings").get("crewlink_pass") ?? "") ==
          //                 ""))) {
          //   return "/crewlink/settings";
          // }
          return null;
        },
        routes: [
          GoRoute(
              path: '/signup',
              builder: (BuildContext context, GoRouterState state) {
                // Access query parameters here
                return Text("signup");
              }),
          GoRoute(
              path: '/login-otp',
              builder: (BuildContext context, GoRouterState state) {
                // Access query parameters here
                final token = state.uri.queryParameters['token'];
                return LoginOtp();
              }),
        ]),
    GoRoute(
      path: '/expired',
      builder: (context, state) => BasicPage(
          appBar: AppBar(
            automaticallyImplyLeading: false,
            title: const Text("TAR Pilot v5"),
          ),
          drawer: ListView(),
          body: const Text("App is Expired please Update")),
    ),
    GoRoute(
      path: '/home',
      redirect: (context, state) => '/crewlink/roster',
    ),
    GoRoute(
      path: '/settings',
      builder: (context, state) {
        final params = (state.extra as SettingsParams?) ?? SettingsParams();
        return SettingsPage(params: params);
      },
    ),
    GoRoute(
      path: '/pdf',
      builder: (context, state) {
        final params = state.extra as PdfPageParams;
        return PdfPage(params: params);
      },
    ),
    GoRoute(
      path: '/rosters',
      builder: (context, state) {
        return const RostersPage();
      },
    ),
    GoRoute(
      path: '/flightslist',
      builder: (context, state) {
        return const FlightslistPage();
      },
    ),
    GoRoute(
      path: '/ftl',
      builder: (context, state) {
        final params = (state.extra as FtlPageParams?) ?? const FtlPageParams();
        return FtlPage(params: params);
      },
    ),
    GoRoute(
      path: '/fltinfo',
      builder: (context, state) {
        final params = (state.extra as FltinfoParams?) ?? const FltinfoParams();
        return FltinfoPage(params: params);
      },
    ),
    GoRoute(
      path: '/dutyinfo',
      builder: (context, state) {
        final params =
            (state.extra as DutyinfoParams?) ?? const DutyinfoParams();
        return DutyinfoPage(params: params);
      },
    ),
    GoRoute(
        path: "/lido",
        redirect: (_, state) {
          // log(state.fullPath.toString());
          if
              // (["/crewlink/roster"].contains(state.uri.toString())&&
              (state.fullPath != "/lido/settings" &&
                  (((Hive.box("settings").get("lido_user") ?? "") == "") ||
                      ((Hive.box("settings").get("lido_pass") ?? "") == ""))) {
            return "/lido/settings";
          }
          return null;
        },
        routes: [
          GoRoute(
              name: "lido.list",
              path: 'list',
              builder: (context, state) {
                final params = (state.extra as LidolistPageParams?) ??
                    const LidolistPageParams();
                return LidolistPage(params: params);
              }),
          GoRoute(
              name: "lido.ofp",
              path: 'ofp',
              builder: (context, state) {
                final params = (state.extra as LidoofpPageParams?) ??
                    const LidoofpPageParams();
                return LidoofpPage(params: params);
              }),
          GoRoute(
              path: 'settings', builder: (context, state) => const LidoForm()),
        ]),
    GoRoute(
        path: "/crewlink",
        redirect: (_, state) {
          // log(state.fullPath.toString());
          if
              // (["/crewlink/roster"].contains(state.uri.toString())&&
              (state.fullPath != "/crewlink/settings" &&
                  (((Hive.box("settings").get("crewlink_user") ?? "") == "") ||
                      ((Hive.box("settings").get("crewlink_pass") ?? "") ==
                          ""))) {
            return "/crewlink/settings";
          }
          return null;
        },
        routes: [
          GoRoute(
              name: "crewlink.roster",
              path: 'roster',
              builder: (context, state) {
                final params = (state.extra as RosterPageParams?) ??
                    const RosterPageParams();

                return RosterPage(
                  params: RosterPageParams(
                      datestart: params.datestart ??
                          Jiffy.now()
                              .toUtc()
                              .startOf(Unit.month)
                              // .subtract(days: 30)
                              .format(pattern: "ddMMMyy"),
                      dateend: params.dateend ??
                          Jiffy.now()
                              .toUtc()
                              .endOf(Unit.month)
                              .format(pattern: "ddMMMyy"),
                      crewlinkuser: params.crewlinkuser ??
                          Hive.box("settings").get("crewlink_user") ??
                          "",
                      crewlinkpass: params.crewlinkpass ??
                          Hive.box("settings").get("crewlink_pass") ??
                          ""),
                );
              }),
          GoRoute(
              name: "crewlink.crewlist",
              path: 'crewlist',
              builder: (context, state) {
                final params = (state.extra as CrewlistPageParams?) ??
                    const CrewlistPageParams();
                print(
                    "${params.datestart} ${params.dateend} ${params.al} ${params.fnum} ${params.dep} ${params.des}");
                return CrewlistPage(
                  params: CrewlistPageParams(
                      datestart: params.datestart ?? //"04Dec23",
                          Jiffy.now()
                              .toUtc()
                              //.subtract(days: 1)
                              .format(pattern: "ddMMMyy"),
                      dateend: params.dateend ?? //"05Dec23",
                          params.datestart ??
                          Jiffy.now().toUtc().format(pattern: "ddMMMyy"),
                      al: params.al ?? "",
                      fnum: params.fnum ?? "",
                      dep: params.dep ?? "",
                      des: params.des ?? "",
                      crewlinkuser: params.crewlinkuser ??
                          Hive.box("settings").get("crewlink_user") ??
                          "",
                      crewlinkpass: params.crewlinkpass ??
                          Hive.box("settings").get("crewlink_pass") ??
                          ""),
                );
              }),
          GoRoute(
              path: 'settings',
              builder: (context, state) => const CrewlinkForm()),
        ])
  ],
);
