import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:logging/logging.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:moneymgr_mobile/providers/auth_state.dart';
import 'package:moneymgr_mobile/services/api/api_token.dart';
import 'package:moneymgr_mobile/services/router/routes_list.dart';
import 'package:moneymgr_mobile/utils/extensions.dart';

class QrAuthScreen extends HookConsumerWidget {
  const QrAuthScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final loading = useState(false);

    handleCapture(BarcodeCapture barcodes) async {
      if (loading.value) return;

      if (barcodes.barcodes.length != 1) return;
      final b = barcodes.barcodes[0];

      if (b.format != BarcodeFormat.qrCode) {
        context.showTextSnackBar(
          "Only QrCode are supported!",
          duration: Duration(seconds: 1),
        );
        return;
      }

      final value = b.rawValue ?? "";

      Logger.root.finest("Decoded QrCode: $value");

      if (!value.startsWith("moneymgr://")) {
        context.showTextSnackBar(
          "Not a MoneyMgr Qr Code!",
          duration: Duration(seconds: 1),
        );
        return;
      }

      // Decode token
      final uri = Uri.parse(
        value.replaceFirst("moneymgr://", "http://test.com/?"),
      );
      final token = ApiToken(
        apiUrl: uri.queryParameters["api"] ?? "",
        tokenId: int.tryParse(uri.queryParameters["id"] ?? "") ?? 0,
        tokenValue: uri.queryParameters["secret"] ?? "",
      );

      // Attempt to authenticate using token
      try {
        loading.value = true;

        await ref.read(currentAuthStateProvider.notifier).setAuthToken(token);

        if (context.mounted) {
          if (context.canPop()) context.pop();
          context.replace(profilePage);
        }
      } catch (e, s) {
        Logger.root.severe("Failed to authenticate user! $e $s");
        if (context.mounted) {
          context.showTextSnackBar("Failed to authenticate user! $e");
        }
      } finally {
        loading.value = false;
      }
    }

    return Scaffold(
      appBar: AppBar(title: Text('QR Authentication')),
      body: MobileScanner(onDetect: handleCapture),
    );
  }
}
