import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:logging/logging.dart';
import 'package:moneymgr_mobile/providers/auth_state.dart';
import 'package:moneymgr_mobile/services/api/api_client.dart';
import 'package:moneymgr_mobile/services/api/auth_api.dart';
import 'package:moneymgr_mobile/services/api/server_api.dart';
import 'package:moneymgr_mobile/widgets/full_screen_error.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'load_startup_data.g.dart';

@riverpod
Future<void> _loadStartupElements(Ref ref) async {
  final svc = ref.watch(apiServiceProvider);
  if (svc == null) {
    throw Exception("API client has not be initialized yet!");
  }

  Logger.root.info("Start to load startup elements");
  await svc.serverConfigOrCache();
  await svc.authInfoOrCache();
  Logger.root.info("Finish to load startup elements");
}

class LoadStartupData extends HookConsumerWidget {
  final Widget child;

  const LoadStartupData({super.key, required this.child});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final serverConfig = ref.watch(_loadStartupElementsProvider);

    tryAgain() async {
      try {
        final val = ref.refresh(_loadStartupElementsProvider);
        Logger.root.info("Load again startup result: $val");
      } catch (e, s) {
        Logger.root.shout("Failed to try again startup loading! $e $s");
      }
    }

    handleSignOut() {
      ref.watch(currentAuthStateProvider.notifier).logout();
    }

    return switch (serverConfig) {
      AsyncData() => child,
      AsyncError(:final error) => FullScreenError(
        message: "Failed to load server configuration!",
        error: error.toString(),
        actions: [
          MaterialButton(
            onPressed: tryAgain,
            child: Text("Try again".toUpperCase()),
          ),
          MaterialButton(
            onPressed: handleSignOut,
            child: Text("Sign out".toUpperCase()),
          ),
        ],
      ),
      _ => const Scaffold(body: Center(child: CircularProgressIndicator())),
    };
  }
}
