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/auth/auth.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';

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

final _routes = GoRouter(
  debugLogDiagnostics: false,
  redirect: (_, s) {
    log("${s.fullPath} | ${s.extra.runtimeType.toString()}", name: "routes");
    if (DateTime.now().isAfter(DateTime(2024, 11, 1))) {
      return "/expired";
    }

    return null;
  },
//  initialLocation: '/test',
  initialLocation: '/crewlink/roster',
  routes: [
    GoRoute(
      path: '/test',
      builder: (context, state) => BasicPage(
        appBar: AppBar(
          automaticallyImplyLeading: false,
          title: const Text("TAR Pilot v5"),
        ),
        drawer: ListView(),
        body: Column(
          children: [
            Text("${Jiffy.parseFromList([
                  2024,
                  9,
                  1,
                  20,
                  0
                ], isUtc: true).setTz(ap: "TUN").toUtc().dateTime}"),
            Text(DTInterval.fromHm(
                    apartir:
                        Jiffy.parseFromList([2024, 9, 1, 1, 1], isUtc: true)
                            .setTz(ap: "TUN"),
                    h: 2,
                    m: 0,
                    duration: const Duration(hours: 2, minutes: 59),
                    ap: "TUN")
                .start
                .dateTime
                .toIso8601String())
          ],
        ),
      ),
    ),
    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: '/login',
      builder: (context, state) => const LoginPage(),
    ),
    GoRoute(
      path: '/verification',
      builder: (context, state) {
        final params = state.extra as VerificationPageParams?;

        if (params == null) {
          throw 'Missing `VerificationPageParams` object';
        }

        return VerificationPage(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("profile").get("lido_user") ?? "") == "") ||
                      ((Hive.box("profile").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("profile").get("crewlink_user") ?? "") == "") ||
                      ((Hive.box("profile").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("profile").get("crewlink_user") ??
                          "",
                      crewlinkpass: params.crewlinkpass ??
                          Hive.box("profile").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("profile").get("crewlink_user") ??
                          "",
                      crewlinkpass: params.crewlinkpass ??
                          Hive.box("profile").get("crewlink_pass") ??
                          ""),
                );
              }),
          GoRoute(
              path: 'settings',
              builder: (context, state) => const CrewlinkForm()),
        ])
  ],
);
