اريد ان يتم تعديل الكود
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(const HotspotApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'MikroTik Hotspot',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
        colorScheme: ColorScheme.fromSwatch(
          primarySwatch: Colors.blue,
          accentColor: Colors.blueAccent,
          brightness: Brightness.light,
        ).copyWith(secondary: const Color(0xFF1565C0)),
        fontFamily: 'Tajawal',
        scaffoldBackgroundColor: const Color(0xFFF5F9FF),
        appBarTheme: const AppBarTheme(
          elevation: 0,
          backgroundColor: Color(0xFF1565C0),
          iconTheme: IconThemeData(color: Colors.white),
          titleTextStyle: TextStyle(
            color: Colors.white,
            fontSize: 22,
            fontWeight: FontWeight.bold,
          ),
        ),
        cardTheme: CardTheme(
          elevation: 2,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
        ),
        inputDecorationTheme: InputDecorationTheme(
          filled: true,
          fillColor: Colors.white,
          border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
        ),
      ),
      home: const AuthCheckScreen(),
    );
  }
}

class AuthCheckScreen extends StatefulWidget {
  const AuthCheckScreen({Key? key}) : super(key: key);

  @override
  State<AuthCheckScreen> createState() => _AuthCheckScreenState();
}

class _AuthCheckScreenState extends State<AuthCheckScreen> {
  bool _checking = true;
  String? _username;

  Future<Map<String, dynamic>> _fetchUserData() async {
    try {
      final response = await http
          .get(Uri.parse('http://172.16.0.1/login?var=json'))
          .timeout(const Duration(seconds: 10));

      if (response.statusCode == 200) {
        final data = json.decode(response.body);

        if (data.containsKey('errors')) {
          return {'error': data['errors'].toString()};
        }

        // مباشرة نعيد البيانات كما هي
        return data;
      } else {
        return {'error': 'خطأ في استجابة الراوتر: ${response.statusCode}'};
      }
    } catch (e) {
      return {'error': 'تعذر الاتصال بالراوتر: ${e.toString()}'};
    }
  }

  String? _extractVariable(String html, String varName) {
    final pattern = RegExp(r'\$\(' + RegExp.escape(varName) + r'\)([^<\s]+)');
    final match = pattern.firstMatch(html);
    if (match != null && match.groupCount >= 1) {
      return match.group(1)?.trim();
    }
    return null;
  }

  @override
  void initState() {
    super.initState();
    _checkLogin();
  }

  Future<void> _checkLogin() async {
    final data = await _fetchUserData();

    if (data.containsKey('error') && data['error'] != null) {
      if (mounted) {
        setState(() {
          _checking = false;
          _username = null;
        });
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (_) => LoginScreen(errorMessage: data['error']),
          ),
        );
      }
      return;
    }

    final loggedIn = data['logged_in'] ?? 'no';

    if (loggedIn == 'yes' || loggedIn == 'on') {
      if (mounted) {
        _username = data['username'] ?? 'مستخدم';

        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder:
                (_) => DashboardScreen(
                  username: _username ?? 'مستخدم',
                  userData: {
                    'logged_in': loggedIn,
                    'mac': data['mac'] ?? '',
                    'ip': data['ip'] ?? '',
                    'bytes_in': data['bytes_in'] ?? '0',
                    'bytes_out': data['bytes_out'] ?? '0',
                    'uptime': data['uptime'] ?? '0s',
                    'session_time_left':
                        data['session_time_left'] ?? 'غير محدود',
                  },
                ),
          ),
        );
      }
    } else {
      if (mounted) {
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (_) => const LoginScreen()),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child:
            _checking
                ? const CircularProgressIndicator()
                : const Text('جارِ التحقق من حالة تسجيل الدخول...'),
      ),
    );
  }
}

class LoginScreen extends StatefulWidget {
  final String? errorMessage;
  const LoginScreen({super.key, this.errorMessage});

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final TextEditingController _usernameController = TextEditingController();
  bool _isLoading = false;
  String _message = '';
  bool _showMessage = false;
  bool _isError = false;

  void _showStatusMessage(String message, {bool isError = false}) {
    setState(() {
      _message = message;
      _showMessage = true;
      _isError = isError;
    });
    Future.delayed(const Duration(seconds: 4), () {
      if (mounted) setState(() => _showMessage = false);
    });
  }

  Future<void> _login() async {
    if (_usernameController.text.isEmpty) {
      _showStatusMessage('يجب إدخال اسم المستخدم', isError: true);
      return;
    }

    setState(() {
      _isLoading = true;
      _showMessage = false;
    });

    try {
      final loginResponse = await http
          .post(
            Uri.parse('http://172.16.0.1/login'),
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: {
              'username': _usernameController.text,
              'password': '',
              'dst': '',
              'popup': 'true',
            },
          )
          .timeout(const Duration(seconds: 10));

      if (loginResponse.statusCode != 200) {
        _showStatusMessage('فشل تسجيل الدخول', isError: true);
        setState(() => _isLoading = false);
        return;
      }

      final responseAfterLogin = await http.get(Uri.parse('http://172.16.0.1'));
      final loggedIn =
          _extractVariable(responseAfterLogin.body, 'logged-in') ?? 'no';

      if (loggedIn == 'yes' || loggedIn == 'on') {
        _showStatusMessage('تم تسجيل الدخول بنجاح', isError: false);
        if (mounted) {
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(
              builder:
                  (context) => DashboardScreen(
                    username: _usernameController.text,
                    userData: {
                      'logged_in': loggedIn,
                      'mac':
                          _extractVariable(responseAfterLogin.body, 'mac') ??
                          '',
                      'ip':
                          _extractVariable(responseAfterLogin.body, 'ip') ?? '',
                      'bytes_in':
                          _extractVariable(
                            responseAfterLogin.body,
                            'bytes-in',
                          ) ??
                          '0',
                      'bytes_out':
                          _extractVariable(
                            responseAfterLogin.body,
                            'bytes-out',
                          ) ??
                          '0',
                      'uptime':
                          _extractVariable(responseAfterLogin.body, 'uptime') ??
                          '0s',
                      'session_time_left':
                          _extractVariable(
                            responseAfterLogin.body,
                            'session-time-left',
                          ) ??
                          'غير محدود',
                    },
                  ),
            ),
          );
        }
      } else {
        _showStatusMessage(
          'فشل تسجيل الدخول. تأكد من صحة البيانات.',
          isError: true,
        );
      }
    } catch (e) {
      _showStatusMessage('حدث خطأ: ${e.toString()}', isError: true);
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  String? _extractVariable(String html, String varName) {
    final pattern = RegExp(r'\$\(' + RegExp.escape(varName) + r'\)([^<\s]+)');
    final match = pattern.firstMatch(html);
    if (match != null && match.groupCount >= 1) {
      return match.group(1)?.trim();
    }
    return null;
  }

  @override
  void initState() {
    super.initState();
    if (widget.errorMessage != null) {
      _showStatusMessage(widget.errorMessage!, isError: true);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('تسجيل الدخول'), centerTitle: true),
      body: Stack(
        children: [
          Container(
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [Color(0xFF1565C0), Color(0xFF0D47A1)],
              ),
            ),
            child: Center(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(24),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const SizedBox(height: 20),
                    const Icon(Icons.wifi, size: 80, color: Colors.white),
                    const SizedBox(height: 20),
                    const Text(
                      'مرحباً بك في شبكة الواي فاي',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 22,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 40),
                    Card(
                      elevation: 8,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(16),
                      ),
                      child: Padding(
                        padding: const EdgeInsets.all(24),
                        child: Column(
                          children: [
                            TextField(
                              controller: _usernameController,
                              decoration: const InputDecoration(
                                labelText: 'اسم المستخدم',
                                prefixIcon: Icon(Icons.person),
                              ),
                            ),
                            const SizedBox(height: 30),
                            SizedBox(
                              width: double.infinity,
                              child: ElevatedButton(
                                onPressed: _isLoading ? null : _login,
                                style: ElevatedButton.styleFrom(
                                  padding: const EdgeInsets.symmetric(
                                    vertical: 16,
                                  ),
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(12),
                                  ),
                                  backgroundColor: const Color(0xFF1565C0),
                                ),
                                child:
                                    _isLoading
                                        ? const SizedBox(
                                          width: 24,
                                          height: 24,
                                          child: CircularProgressIndicator(
                                            color: Colors.white,
                                            strokeWidth: 2,
                                          ),
                                        )
                                        : const Text(
                                          'تسجيل الدخول',
                                          style: TextStyle(fontSize: 16),
                                        ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          if (_showMessage)
            Positioned(
              bottom: 20,
              left: 20,
              right: 20,
              child: AnimatedOpacity(
                opacity: _showMessage ? 1.0 : 0.0,
                duration: const Duration(milliseconds: 300),
                child: Material(
                  elevation: 4,
                  borderRadius: BorderRadius.circular(12),
                  child: Container(
                    padding: const EdgeInsets.all(16),
                    decoration: BoxDecoration(
                      color: _isError ? Colors.red[50] : Colors.green[50],
                      borderRadius: BorderRadius.circular(12),
                      border: Border.all(
                        color: _isError ? Colors.red : Colors.green,
                      ),
                    ),
                    child: Row(
                      children: [
                        Icon(
                          _isError ? Icons.error_outline : Icons.check_circle,
                          color: _isError ? Colors.red : Colors.green,
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: Text(
                            _message,
                            style: TextStyle(
                              color:
                                  _isError
                                      ? Colors.red[800]
                                      : Colors.green[800],
                            ),
                          ),
                        ),
                        IconButton(
                          icon: const Icon(Icons.close, size: 20),
                          onPressed: () => setState(() => _showMessage = false),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }
}

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

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

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

class _DashboardScreenState extends State<DashboardScreen> {
  bool _isLoggingOut = false;
  Timer? _timer;
  late Map<String, dynamic> _currentUserData;

  @override
  void initState() {
    super.initState();
    _currentUserData = widget.userData;
    _startPeriodicUpdate();
  }

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

  void _startPeriodicUpdate() {
    _timer = Timer.periodic(const Duration(seconds: 5), (timer) async {
      await _updateUserData();
    });
  }

  Future<void> _updateUserData() async {
    try {
      final response = await http
          .get(Uri.parse('http://172.16.0.1'))
          .timeout(const Duration(seconds: 10));
      if (response.statusCode == 200) {
        final htmlContent = response.body;
        final loggedIn = _extractVariable(htmlContent, 'logged-in') ?? 'no';
        if (loggedIn != 'yes' && loggedIn != 'on') {
          if (mounted) Navigator.pop(context);
          return;
        }
        if (!mounted) return;
        setState(() {
          _currentUserData = {
            'logged_in': loggedIn,
            'mac': _extractVariable(htmlContent, 'mac') ?? '',
            'ip': _extractVariable(htmlContent, 'ip') ?? 'غير معروف',
            'bytes_in': _formatBytes(
              _extractVariable(htmlContent, 'bytes-in') ?? '0',
            ),
            'bytes_out': _formatBytes(
              _extractVariable(htmlContent, 'bytes-out') ?? '0',
            ),
            'uptime': _formatUptime(
              _extractVariable(htmlContent, 'uptime') ?? '0s',
            ),
            'session_time_left':
                _extractVariable(htmlContent, 'session-time-left') ??
                'غير محدود',
          };
        });
      }
    } catch (_) {}
  }

  Future<void> _logout() async {
    setState(() => _isLoggingOut = true);
    try {
      final response = await http
          .post(
            Uri.parse('http://172.16.0.1/logout'),
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: {'username': widget.username},
          )
          .timeout(const Duration(seconds: 10));
      if (response.statusCode == 200) {
        if (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.toString()}'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      if (mounted) setState(() => _isLoggingOut = false);
    }
  }

  String? _extractVariable(String html, String varName) {
    final pattern = RegExp(r'\$\(' + RegExp.escape(varName) + r'\)([^<\s]+)');
    final match = pattern.firstMatch(html);
    if (match != null && match.groupCount >= 1) {
      return match.group(1)?.trim();
    }
    return null;
  }

  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 _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)} دقيقة';
    }
    return uptime;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('لوحة التحكم'),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _updateUserData,
          ),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            _buildUserCard(),
            const SizedBox(height: 16),
            Expanded(
              child: GridView.count(
                crossAxisCount: 2,
                childAspectRatio: 1.2,
                crossAxisSpacing: 16,
                mainAxisSpacing: 16,
                children: [
                  _buildStatCard(
                    Icons.timer,
                    'مدة الاتصال',
                    _currentUserData['uptime'] ?? 'غير معروف',
                    Colors.blue,
                  ),
                  _buildStatCard(
                    Icons.download,
                    'البيانات المستلمة',
                    _currentUserData['bytes_in'] ?? '0',
                    Colors.purple,
                  ),
                  _buildStatCard(
                    Icons.upload,
                    'البيانات المرسلة',
                    _currentUserData['bytes_out'] ?? '0',
                    Colors.orange,
                  ),
                  _buildStatCard(
                    Icons.access_time,
                    'الوقت المتبقي',
                    _currentUserData['session_time_left'] ?? 'غير محدود',
                    Colors.green,
                  ),
                ],
              ),
            ),
            const SizedBox(height: 16),
            SizedBox(
              width: double.infinity,
              child: ElevatedButton.icon(
                onPressed: _isLoggingOut ? null : _logout,
                icon:
                    _isLoggingOut
                        ? const CircularProgressIndicator(
                          color: Colors.white,
                          strokeWidth: 2,
                        )
                        : const Icon(Icons.logout),
                label: Text(
                  _isLoggingOut ? 'جاري تسجيل الخروج...' : 'تسجيل الخروج',
                ),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.red[400],
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildUserCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Container(
                  width: 60,
                  height: 60,
                  decoration: BoxDecoration(
                    color: Colors.blue[50],
                    shape: BoxShape.circle,
                  ),
                  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(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        'مستخدم Hotspot',
                        style: TextStyle(fontSize: 14, color: Colors.grey[600]),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            _buildInfoRow(
              Icons.computer,
              'عنوان IP:',
              _currentUserData['ip'] ?? 'غير معروف',
            ),
            _buildInfoRow(
              Icons.settings_ethernet,
              'عنوان MAC:',
              _currentUserData['mac'] ?? 'غير معروف',
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildInfoRow(IconData icon, String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      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,
              style: TextStyle(color: Colors.grey[700]),
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStatCard(
    IconData icon,
    String title,
    String value,
    Color color,
  ) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: color.withOpacity(0.1),
                shape: BoxShape.circle,
              ),
              child: Icon(icon, size: 24, color: color),
            ),
            const SizedBox(height: 12),
            Text(
              value,
              style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 4),
            Text(
              title,
              style: TextStyle(fontSize: 14, color: Colors.grey[600]),
            ),
          ],
        ),
      ),
    );
  }
}

بناء على هذة الطريقة المقدمة من الموقع الخاص بالشركة
https://help.mikrotik.com/docs/spaces/ROS/pages/87162881/Hotspot+customisation?utm_source=chatgpt.com