// lib/services/background_location_service.dart

import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:geolocator/geolocator.dart';
import 'package:provider/provider.dart';
import '../Notifiers/HomeScreenNotifier.dart';
import '../services/api_calling.dart';
import 'SharedpreferencesService.dart';

@pragma('vm:entry-point')
void startCallback() {
  FlutterForegroundTask.setTaskHandler(LocationTaskHandler());
}

class LocationTaskHandler extends TaskHandler {
  StreamSubscription<Position>? _stream;
  String? _empId;
  String? _sessionId;

  @override
  Future<void> onStart(DateTime timestamp, TaskStarter starter) async {
    // Load user data
    _empId = await SharedpreferencesService().getString("user");
    _sessionId = await SharedpreferencesService().getString("session");

    // var prov = Provider.of<HomescreenNotifier>(context, listen: false);

    // _empId = prov.empId;
    // _sessionId = prov.session;

    print("DATA : ${_empId}");
    print("DATA : ${_sessionId}");
    if (_empId == null || _sessionId == null) {
      FlutterForegroundTask.updateService(
        notificationTitle: "GEN ERP",
        notificationText: "Please login first",
      );
      return;
    }

    // Start real-time location stream (when moving)
    _stream = Geolocator.getPositionStream(
      locationSettings: const LocationSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 20, // Only send if moved 20 meters
      ),
    ).listen((position) {
      _sendLocationToApi(position);
    });

    // Send first location immediately
    _sendCurrentLocationOnce();

    FlutterForegroundTask.updateService(
      notificationTitle: "GEN ERP",
      notificationText: "Live tracking active",
    );
  }

  Future<void> _sendCurrentLocationOnce() async {
    try {
      final position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high,
        timeLimit: const Duration(seconds: 15),
      );
      await _sendLocationToApi(position);
    } catch (e) {
      if (kDebugMode) print("Initial location failed: $e");
    }
  }

  Future<void> _sendLocationToApi(Position position) async {
    final location = "${position.latitude},${position.longitude}";

    _empId = await SharedpreferencesService().getString("user");
    _sessionId = await SharedpreferencesService().getString("session");
    print("DATA111 : ${_empId}");
    print("DATA111 : ${_sessionId}");

    try {
      final result = await ApiCalling.trackLiveLocationEmpolyeeAPI(
        _empId!,
        _sessionId!,
        location,
      );

      if (result != null && result.error == "0") {
        FlutterForegroundTask.updateService(
          notificationTitle: "GEN ERP",
          notificationText: "Location sent • ${DateTime.now().toString().substring(11, 19)}",
        );
      } else {
        FlutterForegroundTask.updateService(
          notificationText: "Sync failed • Retrying...",
        );
      }
    } catch (e) {
      FlutterForegroundTask.updateService(
        notificationText: "No network • Retrying...",
      );
    }

    // Save last sent time
    final time = DateTime.now().toString().substring(11, 19);
    SharedpreferencesService().saveString("lastLocationTime", time);
  }

  // This runs every 6 minutes (fallback when not moving)
  @override
  void onRepeatEvent(DateTime timestamp) {
    _sendCurrentLocationOnce();
  }

  @override
  Future<void> onDestroy(DateTime timestamp, bool isTimeout) async {
    _stream?.cancel();
  }
}

// Main Service Controller
class BackgroundLocationServiceNew {
  static Future<void> init() async {
     FlutterForegroundTask.init(
      androidNotificationOptions: AndroidNotificationOptions(
        channelId: 'gen_erp_location_channel',
        channelName: 'GEN ERP Tracking',
        channelDescription: 'Sends location every 6 minutes',
        channelImportance: NotificationChannelImportance.HIGH,
        priority: NotificationPriority.HIGH,
        showBadge: true,
       visibility: NotificationVisibility.VISIBILITY_SECRET
      ),
      iosNotificationOptions: const IOSNotificationOptions(),
      foregroundTaskOptions:  ForegroundTaskOptions(
        eventAction: ForegroundTaskEventAction.repeat(360000), // Every 6 minutes
        autoRunOnBoot: false, // Prevents crash on boot
        allowWakeLock: true,
        allowWifiLock: true,
      ),
    );
  }

  static Future<bool> get isRunning => FlutterForegroundTask.isRunningService;

  static Future<void> start() async {
    if (await isRunning) {
      await FlutterForegroundTask.restartService();
    } else {
      await FlutterForegroundTask.startService(
        notificationTitle: 'GEN ERP',
        notificationText: 'Starting location tracking...',
        callback: startCallback,
      );
    }
  }

  static Future<void> stop() async {
    await FlutterForegroundTask.stopService();
  }
}