Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

قم باستخراج البيانات من هذا المكان http://172.16.0.1/login?var=json الخاصة ببيانات…

  1. User

    قم باستخراج البيانات من هذا المكان http://172.16.0.1/login?var=json الخاصة ببيانات التسجيل للعلم ان البيانات { "logged_in" : "yes", "username": "", "mac": "C4%3AD9%3A87%3AB1%3AE2%3AED", "link_login_only" : "http://s.net.ye/login", "ip": "172.16.0.142", "bytes_in": "0", "bytes_out": "0", "remain_bytes_total": "", "session_time_left": "", "uptime": "0s", "session_time_left_secs": "0", "uptime_secs": "0", "trial": "no", "login_by": "", "action" : "onLoggedIn" } وقم بتحسين تصميم الواجهه واريد ان تكون واجهه التسجيل اسم مستخدم فقط واما الارسال اريدة ان يقوم بارسال اسم مستخدم وكلمة مرور فارغة

    للعلم الكود 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(0xFF1976D2)), fontFamily: 'Tajawal', scaffoldBackgroundColor: const Color(0xFFF5F9FF), appBarTheme: const AppBarTheme( elevation: 0, backgroundColor: Color(0xFF1976D2), 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 LoginScreen(), ); } }

    class LoginScreen extends StatefulWidget { const LoginScreen({super.key});

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

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

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

    setState(() {
      _isLoading = true;
      _showMessage = false;
    });
    
    try {
      // Replace with your actual MikroTik Hotspot login URL
      final response = await http
          .post(
            Uri.parse('http://172.16.0.1/login'),
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: {
              'username': _usernameController.text,
              'password': _passwordController.text,
            },
          )
          .timeout(const Duration(seconds: 10));
    
      if (response.statusCode == 200) {
        // Successful login to MikroTik
        _showStatusMessage('تم تسجيل الدخول بنجاح', isError: false);
    
        // Fetch user data from MikroTik API
        final userData = await _fetchUserData(_usernameController.text);
    
        if (mounted) {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder:
                  (context) => DashboardScreen(
                    username: _usernameController.text,
                    userData: userData,
                  ),
            ),
          );
        }
      } else {
        _showStatusMessage(
          'فشل في تسجيل الدخول: ${response.statusCode}',
          isError: true,
        );
      }
    } catch (e) {
      _showStatusMessage('حدث خطأ: ${e.toString()}', isError: true);
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
    

    }

    Future<Map<String, dynamic>> _fetchUserData(String username) async { // Replace with actual API call to MikroTik to get user data await Future.delayed(const Duration(seconds: 1)); // Simulate network delay

    return {
      'uptime': '2 ساعات 45 دقيقة',
      'dataUsed': '1.2 جيجابايت',
      'totalData': '5 جيجابايت',
      'remaining': '3.8 جيجابايت',
      'status': 'متصل',
      'ipAddress': '192.168.1.100',
      'macAddress': '00:1A:2B:3C:4D:5E',
      'loginTime': '2023-05-20 14:30',
    };
    

    }

    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); }); }

    @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('تسجيل الدخول'), centerTitle: true), body: Stack( children: [ SingleChildScrollView( padding: const EdgeInsets.all(24), child: Column( children: [ const SizedBox(height: 40), Image.asset('assets/hotspot.png', height: 180), const SizedBox(height: 40), TextField( controller: _usernameController, decoration: const InputDecoration( labelText: 'اسم المستخدم', prefixIcon: Icon(Icons.person_outline), ), ), const SizedBox(height: 16), TextField( controller: _passwordController, obscureText: true, decoration: const InputDecoration( labelText: 'كلمة المرور', prefixIcon: Icon(Icons.lock_outline), ), ), 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(0xFF1976D2), ), child: _isLoading ? const SizedBox( width: 24, height: 24, child: CircularProgressIndicator( color: Colors.white, strokeWidth: 2, ), ) : const Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(Icons.login, size: 20), SizedBox(width: 8), 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 createState() => _DashboardScreenState(); }

    class _DashboardScreenState extends State { bool _isLoading = false; bool _isLoggingOut = false;

    Future _logout() async { setState(() => _isLoggingOut = true);

    try {
      // Replace with actual MikroTik logout API call
      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);
      }
    }
    

    }

    Future _refreshData() async { setState(() => _isLoading = true); // Here you would fetch updated data from MikroTik await Future.delayed(const Duration(seconds: 1)); setState(() => _isLoading = false); }

    @override Widget build(BuildContext context) { final theme = Theme.of(context);

    return Scaffold(
      appBar: AppBar(
        title: const Text('لوحة التحكم'),
        centerTitle: true,
        actions: [
          IconButton(
            icon:
                _isLoading
                    ? const SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(
                        color: Colors.white,
                        strokeWidth: 2,
                      ),
                    )
                    : const Icon(Icons.refresh),
            onPressed: _isLoading ? null : _refreshData,
          ),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            _buildUserCard(context),
            const SizedBox(height: 16),
            Expanded(
              child: GridView.count(
                crossAxisCount: 2,
                childAspectRatio: 1.2,
                crossAxisSpacing: 16,
                mainAxisSpacing: 16,
                children: [
                  _buildStatCard(
                    icon: Icons.timer,
                    title: 'مدة الاتصال',
                    value: widget.userData['uptime'] ?? 'غير معروف',
                    color: Colors.blue,
                  ),
                  _buildStatCard(
                    icon: Icons.data_usage,
                    title: 'البيانات المستخدمة',
                    value: widget.userData['dataUsed'] ?? 'غير معروف',
                    color: Colors.purple,
                  ),
                  _buildStatCard(
                    icon: Icons.storage,
                    title: 'المتبقي',
                    value:
                        '${widget.userData['remaining'] ?? 'غير معروف'} من ${widget.userData['totalData'] ?? 'غير معروف'}',
                    color: Colors.green,
                  ),
                  _buildStatCard(
                    icon: Icons.network_wifi,
                    title: 'حالة الاتصال',
                    value: widget.userData['status'] ?? 'غير معروف',
                    color:
                        (widget.userData['status'] == 'متصل')
                            ? Colors.teal
                            : Colors.orange,
                  ),
                ],
              ),
            ),
            const SizedBox(height: 16),
            SizedBox(
              width: double.infinity,
              child: ElevatedButton.icon(
                onPressed: _isLoggingOut ? null : _logout,
                icon:
                    _isLoggingOut
                        ? const SizedBox(
                          width: 20,
                          height: 20,
                          child: 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(BuildContext context) { 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:', widget.userData['ipAddress'] ?? 'غير معروف', ), _buildInfoRow( Icons.settings_ethernet, 'عنوان MAC:', widget.userData['macAddress'] ?? 'غير معروف', ), _buildInfoRow( Icons.access_time, 'وقت الدخول:', widget.userData['loginTime'] ?? 'غير معروف', ), ], ), ), ); }

    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({ required IconData icon, required String title, required String value, required 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]), ), ], ), ), ); } }

  2. Assistant

    قمت بمراجعة الكود المرسل، وقمت بالتعديلات المطلوبة كما يلي:

    • تغيير واجهة تسجيل الدخول لتحتوي على حقل اسم مستخدم فقط (بدون حقل كلمة المرور).
    • عند إرسال الطلب، يتم إرسال اسم المستخدم وكلمة مرور فارغة كما طلبت.
    • تعديل دالة _login لكي ترسل كلمة مرور فارغة في الـ body.
    • ضبط تحسينات بسيطة في التصميم لتكون الواجهة مرتبة وواضحة أكثر.

    وهذا الكود المعدّل للواجهة (مع باقي الكود كما هو، يمكنك استبداله داخل مشروعك):

    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(0xFF1976D2)),
            fontFamily: 'Tajawal',
            scaffoldBackgroundColor: const Color(0xFFF5F9FF),
            appBarTheme: const AppBarTheme(
              elevation: 0,
              backgroundColor: Color(0xFF1976D2),
              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 LoginScreen(),
        );
      }
    }
    
    class LoginScreen extends StatefulWidget {
      const LoginScreen({super.key});
    
      @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;
    
      Future<void> _login() async {
        if (_usernameController.text.trim().isEmpty) {
          _showStatusMessage('يجب إدخال اسم المستخدم', isError: true);
          return;
        }
    
        setState(() {
          _isLoading = true;
          _showMessage = false;
        });
    
        try {
          final response = await http
              .post(
                Uri.parse('http://172.16.0.1/login'),
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: {
                  'username': _usernameController.text.trim(),
                  'password': '', // كلمة المرور فارغة
                },
              )
              .timeout(const Duration(seconds: 10));
    
          if (response.statusCode == 200) {
            // استخراج بيانات الـ JSON من الرابط http://172.16.0.1/login?var=json
            final userDataResponse = await http.get(
              Uri.parse('http://172.16.0.1/login?var=json'),
            );
    
            Map<String, dynamic> userData = {};
            if (userDataResponse.statusCode == 200) {
              userData = json.decode(userDataResponse.body) as Map<String, dynamic>;
            }
    
            // تحقق من حالة تسجيل الدخول
            if (userData['logged_in'] == 'yes') {
              _showStatusMessage('تم تسجيل الدخول بنجاح', isError: false);
    
              if (mounted) {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => DashboardScreen(
                      username: _usernameController.text.trim(),
                      userData: userData,
                    ),
                  ),
                );
              }
            } else {
              _showStatusMessage('فشل في تسجيل الدخول', isError: true);
            }
          } else {
            _showStatusMessage(
              'فشل في تسجيل الدخول: ${response.statusCode}',
              isError: true,
            );
          }
        } catch (e) {
          _showStatusMessage('حدث خطأ: ${e.toString()}', isError: true);
        } finally {
          if (mounted) {
            setState(() => _isLoading = 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);
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: const Text('تسجيل الدخول'), centerTitle: true),
          body: Stack(
            children: [
              SingleChildScrollView(
                padding: const EdgeInsets.all(24),
                child: Column(
                  children: [
                    const SizedBox(height: 40),
                    Image.asset('assets/hotspot.png', height: 180),
                    const SizedBox(height: 40),
                    TextField(
                      controller: _usernameController,
                      decoration: const InputDecoration(
                        labelText: 'اسم المستخدم',
                        prefixIcon: Icon(Icons.person_outline),
                      ),
                      textInputAction: TextInputAction.done,
                      onSubmitted: (_) => _isLoading ? null : _login(),
                    ),
                    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(0xFF1976D2),
                        ),
                        child: _isLoading
                            ? const SizedBox(
                                width: 24,
                                height: 24,
                                child: CircularProgressIndicator(
                                  color: Colors.white,
                                  strokeWidth: 2,
                                ),
                              )
                            : const Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Icon(Icons.login, size: 20),
                                  SizedBox(width: 8),
                                  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),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
            ],
          ),
        );
      }
    }
    
    // باقي الكود الخاص باللوحة (DashboardScreen) كما هو لديك...
    
    

    نقاط مهمة:

    • استخدمت http.get للحصول على بيانات JSON من "http://172.16.0.1/login?var=json" بعد نجاح تسجيل الدخول.
    • أرسلت كلمة مرور فارغة كما طلبت.
    • أزلت حقل كلمة المرور من واجهة تسجيل الدخول.
    • ضبطت textInputAction للتمكين من الضغط على زر "تم" في لوحة المفاتيح لتنفيذ التسجيل.
    • حافظت على أسلوب العرض للرسائل بالأسفل مع اللون الأحمر/الأخضر للتنبيه.

    إذا تحتاج مساعدات إضافية في تعديل لوحة التحكم أو أي جزء آخر، فقط أخبرني!

  3. User

    اريد الكود بالكامل دون تعليقات لاقوم باستخدامة مباشرة عبر النسخ والصق دون اي اجرى اخر

  4. Assistant
    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(0xFF1976D2)),
            fontFamily: 'Tajawal',
            scaffoldBackgroundColor: const Color(0xFFF5F9FF),
            appBarTheme: const AppBarTheme(
              elevation: 0,
              backgroundColor: Color(0xFF1976D2),
              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 LoginScreen(),
        );
      }
    }
    
    class LoginScreen extends StatefulWidget {
      const LoginScreen({super.key});
      @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;
    
      Future<void> _login() async {
        if (_usernameController.text.trim().isEmpty) {
          _showStatusMessage('يجب إدخال اسم المستخدم', isError: true);
          return;
        }
        setState(() {
          _isLoading = true;
          _showMessage = false;
        });
        try {
          final response = await http
              .post(
                Uri.parse('http://172.16.0.1/login'),
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: {
                  'username': _usernameController.text.trim(),
                  'password': '',
                },
              )
              .timeout(const Duration(seconds: 10));
          if (response.statusCode == 200) {
            final userDataResponse = await http.get(
              Uri.parse('http://172.16.0.1/login?var=json'),
            );
            Map<String, dynamic> userData = {};
            if (userDataResponse.statusCode == 200) {
              userData = json.decode(userDataResponse.body) as Map<String, dynamic>;
            }
            if (userData['logged_in'] == 'yes') {
              _showStatusMessage('تم تسجيل الدخول بنجاح', isError: false);
              if (mounted) {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => DashboardScreen(
                      username: _usernameController.text.trim(),
                      userData: userData,
                    ),
                  ),
                );
              }
            } else {
              _showStatusMessage('فشل في تسجيل الدخول', isError: true);
            }
          } else {
            _showStatusMessage(
              'فشل في تسجيل الدخول: ${response.statusCode}',
              isError: true,
            );
          }
        } catch (e) {
          _showStatusMessage('حدث خطأ: ${e.toString()}', isError: true);
        } finally {
          if (mounted) {
            setState(() => _isLoading = 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);
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: const Text('تسجيل الدخول'), centerTitle: true),
          body: Stack(
            children: [
              SingleChildScrollView(
                padding: const EdgeInsets.all(24),
                child: Column(
                  children: [
                    const SizedBox(height: 40),
                    Image.asset('assets/hotspot.png', height: 180),
                    const SizedBox(height: 40),
                    TextField(
                      controller: _usernameController,
                      decoration: const InputDecoration(
                        labelText: 'اسم المستخدم',
                        prefixIcon: Icon(Icons.person_outline),
                      ),
                      textInputAction: TextInputAction.done,
                      onSubmitted: (_) => _isLoading ? null : _login(),
                    ),
                    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(0xFF1976D2),
                        ),
                        child: _isLoading
                            ? const SizedBox(
                                width: 24,
                                height: 24,
                                child: CircularProgressIndicator(
                                  color: Colors.white,
                                  strokeWidth: 2,
                                ),
                              )
                            : const Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Icon(Icons.login, size: 20),
                                  SizedBox(width: 8),
                                  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 _isLoading = false;
      bool _isLoggingOut = false;
    
      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);
          }
        }
      }
    
      Future<void> _refreshData() async {
        setState(() => _isLoading = true);
        await Future.delayed(const Duration(seconds: 1));
        setState(() => _isLoading = false);
      }
    
      @override
      Widget build(BuildContext context) {
        final theme = Theme.of(context);
        return Scaffold(
          appBar: AppBar(
            title: const Text('لوحة التحكم'),
            centerTitle: true,
            actions: [
              IconButton(
                icon: _isLoading
                    ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(
                          color: Colors.white,
                          strokeWidth: 2,
                        ),
                      )
                    : const Icon(Icons.refresh),
                onPressed: _isLoading ? null : _refreshData,
              ),
            ],
          ),
          body: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                _buildUserCard(context),
                const SizedBox(height: 16),
                Expanded(
                  child: GridView.count(
                    crossAxisCount: 2,
                    childAspectRatio: 1.2,
                    crossAxisSpacing: 16,
                    mainAxisSpacing: 16,
                    children: [
                      _buildStatCard(
                        icon: Icons.timer,
                        title: 'مدة الاتصال',
                        value: widget.userData['uptime'] ?? 'غير معروف',
                        color: Colors.blue,
                      ),
                      _buildStatCard(
                        icon: Icons.data_usage,
                        title: 'البيانات المستخدمة',
                        value: widget.userData['bytes_in'] ?? 'غير معروف',
                        color: Colors.purple,
                      ),
                      _buildStatCard(
                        icon: Icons.storage,
                        title: 'المتبقي',
                        value:
                            '${widget.userData['remain_bytes_total'] ?? 'غير معروف'}',
                        color: Colors.green,
                      ),
                      _buildStatCard(
                        icon: Icons.network_wifi,
                        title: 'حالة الاتصال',
                        value: widget.userData['logged_in'] == 'yes' ? 'متصل' : 'غير متصل',
                        color:
                            (widget.userData['logged_in'] == 'yes')
                                ? Colors.teal
                                : Colors.orange,
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 16),
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton.icon(
                    onPressed: _isLoggingOut ? null : _logout,
                    icon: _isLoggingOut
                        ? const SizedBox(
                            width: 20,
                            height: 20,
                            child: 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(BuildContext context) {
        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:',
                  widget.userData['ip'] ?? 'غير معروف',
                ),
                _buildInfoRow(
                  Icons.settings_ethernet,
                  'عنوان MAC:',
                  Uri.decodeComponent(widget.userData['mac'] ?? 'غير معروف'),
                ),
                _buildInfoRow(
                  Icons.access_time,
                  'مدة الاتصال:',
                  widget.userData['uptime'] ?? 'غير معروف',
                ),
              ],
            ),
          ),
        );
      }
    
      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({
        required IconData icon,
        required String title,
        required String value,
        required 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]),
                ),
              ],
            ),
          ),
        );
      }
    }