اكمل هذا
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';

class DashboardScreen extends StatefulWidget {
  final String username;
  final Map<String, dynamic> userData;

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

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

class _DashboardScreenState extends State<DashboardScreen> {
  late Map<String, dynamic> currentUserData;
  Timer? updateTimer;
  bool isLoggingOut = false;

  @override
  void initState() {
    super.initState();
    currentUserData = widget.userData;
    _startAutoUpdate();
  }

  void _startAutoUpdate() {
    updateTimer = Timer.periodic(const Duration(seconds: 5), (_) {
      _fetchUserData();
    });
  }

  Future<void> _fetchUserData() async {
    final String baseUrl = dotenv.env['API_BASE_URL'] ?? 'http://172.16.0.1';
    try {
      final res = await http
          .get(Uri.parse('$baseUrl/login?var=json'))
          .timeout(const Duration(seconds: 10));
      if (res.statusCode == 200) {
        final data = json.decode(res.body);
        if (!mounted) return;
        if (!data.containsKey('errors')) {
          setState(() {
            currentUserData = data;
          });
        }
      }
    } catch (_) {
      // تجاهل الأخطاء
    }
  }

  Future<void> _logout() async {
    final String baseUrl = dotenv.env['API_BASE_URL'] ?? 'http://172.16.0.1';
    setState(() => isLoggingOut = true);
    try {
      final res = await http
          .post(
            Uri.parse('$baseUrl/logout'),
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: {'username': widget.username},
          )
          .timeout(const Duration(seconds: 10));

      if (res.statusCode == 200 && mounted) {
        Navigator.pop(context);
      } else if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('فشل في تسجيل الخروج'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('حدث خطأ: $e'), backgroundColor: Colors.red),
        );
      }
    } finally {
      if (mounted) {
        setState(() => isLoggingOut = false);
      }
    }
  }

  String _formatBytes(dynamic bytes) {
    int value = 0;
    if (bytes is String) {
      value = int.tryParse(bytes) ?? 0;
    } else if (bytes is int) {
      value = 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)} جيجابايت';
  }

  String _formatUptime(String uptime) {
    if (uptime.endsWith('s')) {
      final seconds = int.tryParse(uptime.replaceAll('s', '')) ?? 0;
      if (seconds < 60) return '$seconds ثانية';
      if (seconds < 3600) {
        return '${(seconds / 60).floor()} دقيقة ${seconds % 60} ثانية';
      }
      return '${(seconds / 3600).floor()} ساعة ${(seconds % 3600 / 60).floor()} دقيقة';
    }
    return uptime;
  }

  String _decodeMac(String mac) {
    return mac.replaceAll('%3A', ':');
  }

  @override
  void dispose() {
    updateTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final data = currentUserData;
    final ip = data['ip'] ?? 'غير معروف';
    final mac = _decodeMac(data['mac'] ?? 'غير معروف');
    final bytesIn = _formatBytes(data['bytes_in'] ?? '0');
    final bytesOut = _formatBytes(data['bytes_out'] ?? '0');
    final uptime = _formatUptime(data['uptime'] ?? '0s');
    final sessionTimeLeft = data['session_time_left'] ?? 'غير محدود';

    return Scaffold(
      appBar: AppBar(
        title: const Text('لوحة التحكم'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _fetchUserData,
          ),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Row(
                  children: [
                    CircleAvatar(
                      radius: 30,
                      backgroundColor: Colors.blue[50],
                      child: const Icon(
                        Icons.person,
                        size: 30,
                        color: Colors.blue,
                      ),
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            widget.username,
                            style: const TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 18,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            'مستخدم Hotspot',
                            style: TextStyle(color: Colors.grey[600]),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),
            _infoRow(Icons.computer, 'عنوان IP:', ip),
            _infoRow(Icons.settings_ethernet, 'عنوان MAC:', mac),
            const SizedBox(height: 16),
            Expanded(
              child: GridView.count(
                crossAxisCount: 2,
                childAspectRatio: 1.2,
                crossAxisSpacing: 16,
                mainAxisSpacing: 16,
                children: [
                  _statCard(Icons.timer, 'مدة الاتصال', uptime, Colors.blue),
                  _statCard(
                    Icons.download,
                    'البيانات المستلمة',
                    bytesIn,
                    Colors.purple,
                  ),
                  _statCard(
                    Icons.upload,
                    'البيانات المرسلة',
                    bytesOut,
                    Colors.orange,
                  ),
                  _statCard(
                    Icons.access_time,
                    'الوقت المتبقي',
                    sessionTimeLeft,
                    Colors.green,
                  ),
                ],
              ),
            ),
            const SizedBox(height: 16),
            ElevatedButton.icon(
              icon: isLoggingOut
                  ? const SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        color: Colors.white,
                      ),
                    )
                  : const Icon(Icons.logout),
              label: Text(
                isLoggingOut ? 'جاري تسجيل الخروج...' : 'تسجيل الخروج',
              ),
              onPressed: isLoggingOut ? null : _logout,
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.red[400],
                minimumSize: const Size.fromHeight(50),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _infoRow(IconData icon, String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6),
      child: Row(
        children: [
          Icon(icon, size: 20, color: Colors.blue),
          const SizedBox(width: 12),
          Text(label, style: const TextStyle(fontWeight: FontWeight.bold)),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              value,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(color: Colors.grey[700]),
            ),
          ),
        ],
      ),
    );
  }

  Widget _statCard(IconData icon, String title, String value, Color color) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 8),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircleAvatar