import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:logger/logger.dart';
import 'package:sigap/src/cores/services/edge_function_service.dart';
import 'package:sigap/src/features/auth/data/models/face_model.dart';
import 'package:sigap/src/features/auth/presentasion/controllers/signup/step/selfie-verification/face_liveness_detection_controller.dart';
 
/// Service for handling facial verification
/// This class serves as a bridge between UI controllers and face detection functionality
class FacialVerificationService {
  // Singleton pattern
  static final FacialVerificationService _instance =
      FacialVerificationService._();
  static FacialVerificationService get instance => _instance;

  // Private constructor
  FacialVerificationService._();

  // Edge Function Service for actual API calls
  final EdgeFunctionService _edgeFunctionService = EdgeFunctionService.instance;

  // Flag for skipping verification in development mode
  bool skipFaceVerification = true;

  /// Set development mode settings
  void setDevelopmentMode({bool skipVerification = true}) {
    skipFaceVerification = skipVerification;
    Logger().i(
      'Face verification development mode settings updated: skipVerification=$skipVerification',
    );
  }

  /// Get all faces in an image using edge function
  Future<List<FaceModel>> detectFaces(XFile image) async {
    if (skipFaceVerification) {
      return [_createDummyFaceModel(image.path)];
    }

    return await _edgeFunctionService.detectFaces(image);
  }

  /// Detect if there is a face in the image
  Future<bool> detectFaceInImage(XFile image) async {
    if (skipFaceVerification) return true;

    try {
      final detectedFaces = await _edgeFunctionService.detectFaces(image);
      return detectedFaces.isNotEmpty;
    } catch (e) {
      print('Error detecting face. Please try again later.');
      return false;
    }
  }

  /// Compare faces between two images using edge function
  Future<FaceComparisonResult> compareFaces(
    XFile source,
    XFile target, {
    FaceModel? sourceModel,
    FaceModel? targetModel,
  }) async {
    if (skipFaceVerification) {
      return _createDummyComparisonResult(source.path, target.path);
    }

    return await _edgeFunctionService.compareFaces(
      source,
      target,
      sourceModel: sourceModel,
      targetModel: targetModel,
    );
  }

  /// Start liveness check - this will navigate to the liveness check screen
  /// and return a model with the captured image if successful
  Future<FaceModel> startLivenessCheck(BuildContext context) async {
    if (skipFaceVerification) {
      // Mock the process for development mode
      return _createDummyFaceModel("dummy_path", isLive: true);
    }

    // In a real implementation, this would navigate to the liveness check screen
    // and return the result when complete.
    // For now, we're just returning a placeholder model

    final livenessController = Get.find<FaceLivenessController>();

    // Wait for liveness check to complete
    // This is a placeholder - in a real implementation we would wait for the
    // liveness check screen to return a result

    // Return placeholder model
    return FaceModel.empty().withLiveness(
      isLive: false,
      confidence: 0.0,
      message: 'Liveness check not implemented yet',
    );
  }

  // Enable development mode
  void enableDevMode() {
    skipFaceVerification = true;
    Logger().i('Development mode enabled for facial verification');
  }

  // Disable development mode
  void disableDevMode() {
    skipFaceVerification = false;
    Logger().i('Development mode disabled for facial verification');
  }

  // Helper methods for development mode
  FaceModel _createDummyFaceModel(String imagePath, {bool isLive = false}) {
    return FaceModel(
      imagePath: imagePath,
      faceId: 'dummy-face-${DateTime.now().millisecondsSinceEpoch}',
      confidence: 0.95,
      boundingBox: {'x': 0.1, 'y': 0.1, 'width': 0.8, 'height': 0.8},
    ).withLiveness(
      isLive: isLive,
      confidence: isLive ? 0.92 : 0.0,
      message:
          isLive
              ? 'Liveness check passed (development mode)'
              : 'Basic face detection only (development mode)',
    );
  }

  FaceComparisonResult _createDummyComparisonResult(
    String sourcePath,
    String targetPath,
  ) {
    final sourceFace = _createDummyFaceModel(sourcePath);
    final targetFace = _createDummyFaceModel(targetPath, isLive: true);

    return FaceComparisonResult(
      sourceFace: sourceFace,
      targetFace: targetFace,
      isMatch: true,
      confidence: 0.91,
      similarity: 91.0,
      similarityThreshold: 75.0,
      confidenceLevel: "HIGH",
      message: 'Face matching successful (development mode)',
    );
  }
}
