import 'dart:async';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:flutter_background_service_android/flutter_background_service_android.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:proxibuy/services/mqtt_service.dart';

const notificationChannelId = 'proxibuy_foreground_service';
const notificationId = 888;

@pragma('vm:entry-point')
void onStart(ServiceInstance service) async {
  DartPluginRegistrant.ensureInitialized();

  final MqttService mqttService = MqttService();
  const storage = FlutterSecureStorage();

  if (service is AndroidServiceInstance) {
    service.setForegroundNotificationInfo(
      title: "ProxiBuy فعال است",
      content: "در حال یافتن تخفیف های اطراف شما...",
    );

    service.on('setAsForeground').listen((event) {
      service.setAsForegroundService();
    });

    service.on('setAsBackground').listen((event) {
      service.setAsBackgroundService();
    });
  }

  service.on('stopService').listen((event) {
    service.stopSelf();
  });

  Timer.periodic(const Duration(seconds: 30), (timer) async {
    debugPrint("✅ Background Service is running and sending location...");

    var locationStatus = await Permission.location.status;
    var locationAlwaysStatus = await Permission.locationAlways.status;
    if (!locationStatus.isGranted || !locationAlwaysStatus.isGranted) {
      debugPrint("Background Service: Permissions not granted. Task skipped.");
      return;
    }

    final position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    final token = await storage.read(key: 'accessToken');
    final userID = await storage.read(key: 'userID');

    if (token != null && token.isNotEmpty && userID != null) {
      if (!mqttService.isConnected) {
        await mqttService.connect(token);
      }
      
      if (mqttService.isConnected) {
          final payload = {"userID": userID, "lat": position.latitude, "lng": position.longitude};
          mqttService.publish("proxybuy/sendGps", payload);
          debugPrint("Background Service: GPS sent successfully.");
      }
    }
  });
}

Future<void> initializeService() async {
  final service = FlutterBackgroundService();

  const AndroidNotificationChannel channel = AndroidNotificationChannel(
    notificationChannelId,
    'ProxiBuy Background Service',
    description: 'This channel is used for location service notifications.',
    importance: Importance.low,
  );

  final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
  
  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(channel);

    await service.configure(
    androidConfiguration: AndroidConfiguration(
      onStart: onStart,
      isForegroundMode: true,
      autoStart: true,
      notificationChannelId: notificationChannelId,
      initialNotificationTitle: 'ProxiBuy فعال است',
      initialNotificationContent: 'در حال جستجو برای تخفیف‌های اطراف شما...',
      foregroundServiceNotificationId: notificationId,
    ),
    iosConfiguration: IosConfiguration(
      autoStart: true,
      onForeground: onStart,
    ),
  );
}