import 'dart:async';
import 'dart:developer';
import 'package:app_links/app_links.dart';
import 'package:flutter/material.dart';
import 'package:hub/features/storage/index.dart';
import 'package:hub/flutter_flow/flutter_flow_theme.dart';
import 'package:hub/flutter_flow/nav/nav.dart';
import 'package:hub/pages/forgot_password_page/forgot_password_screen.dart';

class DeepLinkService {
  static final DeepLinkService _instance = DeepLinkService._internal();

  factory DeepLinkService() => _instance;

  DeepLinkService._internal();

  late final AppLinks _appLinks;
  StreamSubscription<Uri>? _linkSubscription;
  bool _isInitialized = false;

  void ensureInitialization() async {
    if (_isInitialized) return;
    try {
      _appLinks = AppLinks();
      print('initDeepLinks');
      _linkSubscription = _appLinks.uriLinkStream.listen((uri) async {
        if (!StorageHelper().isRecovered) {
          await _handleDeepLink(uri);
        }
      });
      _isInitialized = true;
    } catch (e) {
      print('Error initializing deep links: $e');
    }
  }

  Future<void> _handleDeepLink(Uri uri) async {
    try {
      print('Handling deep link: $uri');
      if (StorageHelper().isRecovered) return;

      StorageHelper().isRecovered = true;
      final email = uri.queryParameters['email'] ?? '';
      final token = uri.queryParameters['token'] ?? '';
      print('email: $email, token: $token');

      if (email.isNotEmpty && token.isNotEmpty) {
        await _showForgotPasswordScreen(email, token);
      }
    } catch (e, s) {
      print('Error handling deep link: $e, $s');
    }
  }

  Future<void> _showForgotPasswordScreen(String email, String token) async {
    try {
      WidgetsBinding.instance.addPostFrameCallback((_) async {
        await showModalBottomSheet(
          context: navigatorKey.currentContext!,
          builder: (context) => Padding(
            padding: MediaQuery.viewInsetsOf(context),
            child: ForgotPasswordScreen(
              key: ValueKey('ForgotPasswordScreen'),
              email: email,
              token: token,
            ),
          ),
          isScrollControlled: true,
          backgroundColor: FlutterFlowTheme.of(navigatorKey.currentContext!)
              .primaryBackground,
          showDragHandle: true,
          useSafeArea: true,
          enableDrag: true,
        ).whenComplete(() {
          StorageHelper().isRecovered = false;
          print('showModalBottomSheet completed');
        });
      });
    } catch (e, s) {
      print('Error showing forgot password screen: $e, $s');
    }
  }

  void dispose() {
    _linkSubscription?.cancel();
  }
}
