صحح الكود
import 'dart:async';
import 'dart:convert';
import 'dart:isolate';

import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:http/http.dart' as http;

const String networkMonitorChannelId = 'network_monitor_channel';

// ========= وظائف تنسيق البيانات ============

String _formatBytes(String bytes) {
  try {
    final value = int.parse(bytes);
    if (value < 1024) return '$value بايت';
    if (value < 1024 * 1024)
      return '${(value / 1024).toStringAsFixed(1)} كيلوبايت';
    if (value < 1024 * 1024 * 1024)
      return '${(value / (1024 * 1024)).toStringAsFixed(1)} ميجابايت';
    return '${(value / (1024 * 1024 * 1024)).toStringAsFixed(1)} جيجابايت';
  } catch (_) {
    return bytes;
  }
}

String _formatUptimeExtended(String uptime) {
  final regex = RegExp(r'(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?');
  final match = regex.firstMatch(uptime);
  if (match == null) return uptime;

  final days = int.tryParse(match.group(1) ?? '0') ?? 0;
  final hours = int.tryParse(match.group(2) ?? '0') ?? 0;
  final minutes = int.tryParse(match.group(3) ?? '0') ?? 0;
  final seconds = int.tryParse(match.group(4) ?? '0') ?? 0;

  String result = '';
  if (days > 0) result += '$days يوم ';
  if (hours > 0) result += '$hours ساعة ';
  if (minutes > 0) result += '$minutes دقيقة ';
  if (seconds > 0) result += '$seconds ثانية';

  return result.trim();
}

String _formatSessionTimeLeft(String sessionTimeLeft) {
  if (sessionTimeLeft == 'غير محدود') return sessionTimeLeft;
  return _formatUptimeExtended(sessionTimeLeft);
}

// === اعداد local notifications ===

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

const AndroidNotificationChannel channel = AndroidNotificationChannel(
  networkMonitorChannelId,
  'Network Monitor',
  description: 'قناة مراقبة حالة الشبكة',
  importance: Importance.low,
  playSound: false,
  enableVibration: false,
);

// ===== foreground task handler ======

void startCallback() {
  FlutterForegroundTask.setTaskHandler(NetworkMonitorTaskHandler());
}

class NetworkMonitorTaskHandler implements TaskHandler {
  Timer? _timer;

  @override
  Future<void> onStart(DateTime timestamp, SendPort? sendPort) async {
    // بدء تيمر كل 15 دقيقة بشكل دوري
    _timer = Timer.periodic(const Duration(minutes: 15), (timer) async {
      await _fetchAndUpdateNotification();
    });

    // استدعاء فوري عند بداية الخدمة
    await _fetchAndUpdateNotification();
  }

  @override
  Future<void> onEvent(DateTime timestamp, SendPort? sendPort) async {
    // لا حاجة بالتنفيذ الإضافي هنا حالياً
  }

  @override
  Future<void> onDestroy(DateTime timestamp, SendPort? sendPort) async {
    _timer?.cancel();
  }

  @override
  void onButtonPressed(String id) {}

  @override
  void onNotificationTap() {}

  Future<void> _fetchAndUpdateNotification() async {
    try {
      final res = await http
          .get(Uri.parse('http://172.16.0.1/status?var=json'))
          .timeout(const Duration(seconds: 5));

      if (res.statusCode == 200) {
        final data = json.decode(res.body);
        if (!data.containsKey('errors')) {
          String body =
              'مدة الاتصال: ${_formatUptimeExtended(data['uptime'] ?? '0s')}\n'
              'المستلم: ${_formatBytes(data['bytes_in']?.toString() ?? '0')}\n'
              'المرسل: ${_formatBytes(data['bytes_out']?.toString() ?? '0')}\n'
              'الوقت المتبقي: ${_formatSessionTimeLeft(data['session_time_left'] ?? 'غير محدود')}\n'
              'المتبقي: ${_formatBytes(data['remain_bytes_total']?.toString() ?? '0')}\n'
              'حالة الاتصال: نشط';

          await FlutterForegroundTask.updateService(
            notificationTitle: 'حالة الشبكة',
            notificationText: body,
          );
        } else {
          await FlutterForegroundTask.stopService();
        }
      } else {
        await FlutterForegroundTask.stopService();
      }
    } catch (_) {
      await FlutterForegroundTask.stopService();
    }
  }
}

// ===== البرنامج الرئيسي =====

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  const AndroidInitializationSettings androidSettings =
      AndroidInitializationSettings('@mipmap/ic_launcher');

  const InitializationSettings initSettings = InitializationSettings(
    android: androidSettings,
  );

  await flutterLocalNotificationsPlugin.initialize(initSettings);

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

  await FlutterForegroundTask.init(
    androidNotificationOptions: AndroidNotificationOptions(
      channelId: networkMonitorChannelId,
      channelName: 'Network Monitor',
      channelDescription: 'قناة مراقبة حالة الشبكة',
      channelImportance: NotificationChannelImportance.LOW,
      priority: NotificationPriority.LOW,
    ),
    iosNotificationOptions: const IOSNotificationOptions(),
  );

 await FlutterForegroundTask.startService(
  notificationTitle: 'Network Monitor',
  notificationText: 'قيد التشغيل...',
  callback: startCallback,
);

  // تعيين callback الخاص بـ foreground task
  FlutterForegroundTask.setTaskHandler(NetworkMonitorTaskHandler());

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: const DashboardScreen(username: "User123"),
      debugShowCheckedModeBanner: false,
    );
  }
}

class DashboardScreen extends StatefulWidget {
  final String username;

  const DashboardScreen({Key? key, required this.username}) : super(key: key);

  @override
  State<DashboardScreen> createState() => _DashboardScreenState();
}

class _DashboardScreenState extends State<DashboardScreen> {
  Timer? _timer;
  Map<String, dynamic> _currentUserData = {
    'ip': '...',
    'mac': '...',
    'bytes_in': '0',
    'bytes_out': '0',
    'remain_bytes_total': '0',
    'uptime': '0s',
    'session_time_left': 'غير محدود',
  };

  @override
  void initState() {
    super.initState();
    _startForegroundTask();
    _startPeriodicFetch();
  }

Future<void> _startForegroundTask() async {
    bool isRunning = await FlutterForegroundTask.isRunningService;
    if (!isRunning) {
     @pragma('vm:entry-point')
void startCallback() {
  FlutterForegroundTask.setTaskHandler(MyTaskHandler());
}

class MyTaskHandler extends TaskHandler {
  int _count = 0;

  @override
  Future<void> onStart(DateTime timestamp, TaskStarter starter) async {
    print('onStart(starter: ${starter.name})');
  }

  @override
  void onRepeatEvent(DateTime timestamp) {
    _count++;

    if (_count == 10) {
      FlutterForegroundTask.updateService(
        notificationTitle: 'Hello FirstTaskHandler :)',
        notificationText: timestamp.toString(),
      );
      return;
    }

    FlutterForegroundTask.updateService(
      notificationTitle: 'Hello FirstTaskHandler :)',
      notificationText: timestamp.toString(),
    );

    final Map<String, dynamic> data = {
      "timestampMillis": timestamp.millisecondsSinceEpoch,
    };
    FlutterForegroundTask.sendDataToMain(data);
  }

  @override
  Future<void> onDestroy(DateTime timestamp, bool isTimeout) async {
    print('onDestroy(isTimeout: $isTimeout)');
  }
}

Future<void> _startForegroundTask() async {
  bool isRunning = await FlutterForegroundTask.isRunningService;
  if (!isRunning) {
    await FlutterForegroundTask.startService(
      notificationTitle: 'جاري مراقبة حالة الشبكة',
      notificationText: 'يتم تحديث البيانات في الخلفية',
      callback: startCallback,
    );
  }
}

      await FlutterForegroundTask.startService(
        notificationTitle: 'جاري مراقبة حالة الشبكة',
        notificationText: 'يتم تحديث البيانات في الخلفية',
        callback: startCallback,
      );
    }
  }


  @override
  void dispose() {
    _timer?.cancel();
    cancelNetworkNotification();
    FlutterForegroundTask.stopService();
    super.dispose();
  }

  Future<void> _fetchStatus() async {
    try {
      final res = await http
          .get(Uri.parse('http://172.16.0.1/status?var=json'))
          .timeout(const Duration(seconds: 2));
      if (res.statusCode == 200) {
        final data = json.decode(res.body);
        if (data.containsKey('errors')) {
          await cancelNetworkNotification();
          return;
        }

        setState(() {
          _currentUserData = {
            'ip': data['ip'] ?? 'غير معروف',
            'mac': data['mac']?.replaceAll('%3A', ':') ?? 'غير معروف',
            'bytes_in': _formatBytes(data['bytes_in']?.toString() ?? '0'),
            'bytes_out': _formatBytes(data['bytes_out']?.toString() ?? '0'),
            'remain_bytes_total': _formatBytes(
              data['remain_bytes_total']?.toString() ?? '0',
            ),
            'uptime': _formatUptimeExtended(data['uptime'] ?? '0s'),
            'session_time_left': _formatSessionTimeLeft(
              data['session_time_left'] ?? 'غير محدود',
            ),
          };
        });

        await showNetworkNotification(
          title: "حالة الشبكة - ${widget.username}",
          body: _buildNotificationBody(_currentUserData),
        );
      } else {
        await cancelNetworkNotification();
      }
    } catch (_) {
      await cancelNetworkNotification();
    }
  }

  void _startPeriodicFetch() {
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (_) => _fetchStatus());
    _fetchStatus();
  }

  String _buildNotificationBody(Map<String, dynamic> data) {
    return 'مدة الاتصال: ${data['uptime']}\n'
        'المستلم: ${data['bytes_in']}\n'
        'المرسل: ${data['bytes_out']}\n'
        'الوقت المتبقي: ${data['session_time_left']}\n'
        'المتبقي: ${data['remain_bytes_total']}\n'
        'حالة الاتصال: نشط';
  }

  Future<void> showNetworkNotification({
    required String title,
    required String body,
  }) async {
    AndroidNotificationDetails androidDetails = AndroidNotificationDetails(
      channel.id,
      channel.name,
      channelDescription: channel.description,
      importance: Importance.low,
      priority: Priority.low,
      ticker: 'ticker',
      ongoing: true,
      autoCancel: false,
      playSound: false,
      enableVibration: false,
      icon: '@mipmap/ic_launcher',
      styleInformation: BigTextStyleInformation(body),
    );

    NotificationDetails notificationDetails = NotificationDetails(
      android: androidDetails,
    );

    await flutterLocalNotificationsPlugin.show(
      888,
      title,
      body,
      notificationDetails,
    );
  }

  Future<void> cancelNetworkNotification() async {
    await flutterLocalNotificationsPlugin.cancel(888);
  }

  Widget _buildUserCard() {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(16),
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 10,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          Row(
            children: [
              Container(
                width: 60,
                height: 60,
                decoration: BoxDecoration(
                  color: const Color(0xFF3366FF).withOpacity(0.1),
                  shape: BoxShape.circle,
                ),
                child: const Icon(
                  Icons.person_rounded,
                  size: 30,
                  color: Color(0xFF3366FF),
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      widget.username,
                      style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        fontFamily: 'Tajawal',
                        color: Color(0xFF2E384D),
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 4),
                    const Text(
                      'بيانات المستخدم',
                      style: TextStyle(
                        fontSize: 14,
                        color: Color(0xFF8798AD),
                        fontFamily: 'Tajawal',
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          Divider(color: Colors.grey.withOpacity(0.2), height: 1),
          const SizedBox(height: 12),
          _buildInfoRow(
            Icons.wifi_rounded,
            'عنوان IP:',
            _currentUserData['ip'],
            const Color(0xFF2E384D),
          ),
          _buildInfoRow(
            Icons.device_hub_rounded,
            'عنوان MAC:',
            _currentUserData['mac'],
            const Color(0xFF2E384D),
          ),
        ],
      ),
    );
  }

  Widget _buildInfoRow(IconData icon, String label, String value, Color color) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        children: [
          Icon(icon, size: 20, color: color.withOpacity(0.6)),
          const SizedBox(width: 12),
          Text(
            label,
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontFamily: 'Tajawal',
              fontSize: 15,
              color: color.withOpacity(0.8),
            ),
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              value,
              style: TextStyle(
                color: color,
                overflow: TextOverflow.ellipsis,
                fontFamily: 'Tajawal',
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStatCard({
    required IconData icon,
    required String title,
    required String value,
    required Color color,
  }) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 10,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: color.withOpacity(0.1),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Icon(icon, size: 24, color: color),
            ),
            const SizedBox(height: 12),
            Text(
              value,
              style: const TextStyle(
                fontFamily: 'Tajawal',
                fontSize: 16,
                fontWeight: FontWeight.bold,
                color: Color(0xFF2E384D),
              ),
            ),
            const SizedBox(height: 4),
            Text(
              title,
              style: const TextStyle(
                fontFamily: 'Tajawal',
                fontSize: 13,
                color: Color(0xFF8798AD),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Directionality(
      textDirection: TextDirection.rtl,
      child: Scaffold(
        backgroundColor: const Color(0xFFF8FAFD),
        appBar: AppBar(
          title: const Text('لوحة التحكم'),
          actions: [
            IconButton(
              icon: const Icon(Icons.logout_rounded),
              tooltip: 'تسجيل الخروج',
              onPressed: () async {
                await cancelNetworkNotification();
                await FlutterForegroundTask.stopService();
                if (mounted) Navigator.of(context).pop();
              },
            ),
          ],
        ),
        body: SafeArea(
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                _buildUserCard(),
                const SizedBox(height: 24),
                GridView.count(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  crossAxisCount: 2,
                  childAspectRatio: 1.1,
                  crossAxisSpacing: 16,
                  mainAxisSpacing: 16,
                  children: [
                    _buildStatCard(
                      icon: Icons.timer_rounded,
                      title: 'مدة الاتصال',
                      value: _currentUserData['uptime'],
                      color: const Color(0xFF3366FF),
                    ),
                    _buildStatCard(
                      icon: Icons.download_rounded,
                      title: 'البيانات المستلمة',
                      value: _currentUserData['bytes_in'],
                      color: const Color(0xFF00C1D4),
                    ),
                    _buildStatCard(
                      icon: Icons.upload_rounded,
                      title: 'البيانات المرسلة',
                      value: _currentUserData['bytes_out'],
                      color: const Color(0xFFFF8A34),
                    ),
                    _buildStatCard(
                      icon: Icons.access_time_filled_rounded,
                      title: 'الوقت المتبقي',
                      value: _currentUserData['session_time_left'],
                      color: const Color(0xFF50B83C),
                    ),
                    _buildStatCard(
                      icon: Icons.data_usage_rounded,
                      title: 'البيانات المتبقية',
                      value: _currentUserData['remain_bytes_total'],
                      color: const Color(0xFF9C6ADE),
                    ),
                    _buildStatCard(
                      icon: Icons.network_check_rounded,
                      title: 'حالة الاتصال',
                      value: 'نشط',
                      color: const Color(0xFFF7C948),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}