import 'dart:async';
import 'package:cloudflare_turnstile/cloudflare_turnstile.dart';
import 'package:flutter/foundation.dart';
import 'package:hmg_patient_app_new/services/logger_service.dart';

/// Service to handle Cloudflare Turnstile captcha verification
class TurnstileService {
  final LoggerService _loggerService;

  // Replace with your Cloudflare Turnstile site key
  static const String _siteKey = '0x4AAAAAAAkmbvEy63pcxBBt';

  TurnstileService(this._loggerService);

  /// Get Turnstile token using invisible mode
  /// Returns the token on success, null on failure
  Future<String?> getTurnstileToken() async {
    // Initialize an instance of invisible Cloudflare Turnstile with your site key
    final turnstile = CloudflareTurnstile.invisible(
      siteKey: _siteKey,
      onTimeout: () {},
      options: TurnstileOptions(
        retryInterval: const Duration(milliseconds: 2000),
      ),
    );

    try {
      // Get the Turnstile token
      final token = await turnstile.getToken();
      _loggerService.logInfo('Turnstile token retrieved successfully');
      return token; // Return the token upon success
    } on TurnstileException catch (e) {
      // Handle Turnstile failure
      _loggerService.logError('Turnstile challenge failed: ${e.message}');
      if (kDebugMode) {
        print('Challenge failed: ${e.message}');
      }
    } catch (e) {
      // Handle any other exceptions
      _loggerService.logError('Unexpected error during Turnstile challenge: $e');
      if (kDebugMode) {
        print('Unexpected error: $e');
      }
    } finally {
      // Ensure the Turnstile instance is properly disposed of
      turnstile.dispose();
    }

    // Return null if the token couldn't be generated
    return null;
  }

  /// Get the site key for Turnstile widget
  String getSiteKey() => _siteKey;

  /// Validate if Turnstile is properly configured
  bool isConfigured() {
    return _siteKey.isNotEmpty && _siteKey != '0x4AAAAAAAkmbvEy63pcxBBt';
  }
}
