import 'package:siro_rider/print.dart';
import 'dart:io';
import 'dart:convert';
import 'package:live_activities/live_activities.dart';

class IosLiveActivityService {
  static final _liveActivitiesPlugin = LiveActivities();
  static String? _activityId;

  static void init() {
    if (Platform.isIOS) {
      _liveActivitiesPlugin.init(
        appGroupId: "group.com.Siro.siro",
      );
    }
  }

  static Future<void> startRideActivity({
    required String rideId,
    required String driverName,
    required String carDetails,
    required String etaText,
    required double progress,
  }) async {
    if (!Platform.isIOS) return;

    try {
      await _liveActivitiesPlugin.endAllActivities();

      // استخدام dynamic يسمح للحزمة بحفظ النصوص والأرقام في الذاكرة المشتركة
      final Map<String, dynamic> activityModel = {
        'status': 'waiting',
        'driverName': driverName,
        'carDetails': carDetails,
        'etaText': etaText,
        'progress': progress,
      };

      // الدالة هنا تأخذ المعاملات مباشرة
      _activityId = await _liveActivitiesPlugin.createActivity(
        rideId,
        activityModel,
      );
    } catch (e) {
      Log.print("❌ Live Activity Start Error: $e");
    }
  }

  static Future<void> updateRideActivity({
    required String status,
    required String driverName,
    required String carDetails,
    required String etaText,
    required double progress,
  }) async {
    if (!Platform.isIOS || _activityId == null) return;

    final Map<String, dynamic> updatedModel = {
      'status': status,
      'driverName': driverName,
      'carDetails': carDetails,
      'etaText': etaText,
      'progress': progress,
    };

    await _liveActivitiesPlugin.updateActivity(_activityId!, updatedModel);
  }

  static Future<void> endRideActivity() async {
    if (!Platform.isIOS || _activityId == null) return;
    await _liveActivitiesPlugin.endActivity(_activityId!);
    _activityId = null;
  }
}