قم بتصحيح الكود التالي
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:http/http.dart' as http;
import 'dashboard_screen.dart';

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

  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

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

    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1400),
    );
    _animation = CurvedAnimation(parent: _controller, curve: Curves.easeInOut);
    _controller.repeat(reverse: true);

    Timer(const Duration(seconds: 3), () {
      Navigator.of(context).pushReplacement(
        MaterialPageRoute(builder: (_) => const AuthCheckScreen()),
      );
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF1565C0),
      body: Center(
        child: FadeTransition(
          opacity: _animation,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: const [
              Icon(Icons.wifi, size: 120, color: Colors.white),
              SizedBox(height: 20),
              Text(
                'شبكة الواي فاي',
                style: TextStyle(
                  fontFamily: 'Tajawal',
                  color: Colors.white,
                  fontSize: 26,
                  fontWeight: FontWeight.bold,
                  letterSpacing: 1.3,
                ),
              ),
              SizedBox(height: 40),
              SpinKitFadingCircle(color: Colors.white, size: 50.0),
            ],
          ),
        ),
      ),
    );
  }
}

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;
  Map<String, String> cookies = {};

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

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

  void _updateCookies(http.Response response) {
    final setCookie = response.headers['set-cookie'];
    if (setCookie != null) {
      final parts = setCookie.split(',');
      for (var part in parts) {
        var cookieItems = part.split(';');
        if (cookieItems.isNotEmpty) {
          var keyValue = cookieItems[0].split('=');
          if (keyValue.length == 2) {
            cookies[keyValue[0].trim()] = keyValue[1];
          }
        }
      }
    }
  }

  String _getCookieHeader() {
    String cookie = '';
    cookies.forEach((key, value) {
      if (cookie.isNotEmpty) cookie += '; ';
      cookie += '$key=$value';
    });
    return cookie;
  }

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

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

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

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

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

        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder:
                (_) => DashboardScreen(
                  username: username,
                  userData: {
                    'logged_in': loggedIn,
                    'username': username,
                    'mac': data['mac'] ?? '',
                    'ip': data['ip'] ?? '',
                    'bytes_in': data['bytes_in'] ?? '0',
                    'bytes_out': data['bytes_out'] ?? '0',
                    'remain_bytes_total': data['remain_bytes_total'] ?? '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 SpinKitCircle(color: Color(0xFF1565C0), size: 60)
                : const Text('جارِ التحقق من حالة تسجيل الدخول...'),
      ),
    );
  }
}

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;

  Map<String, String> cookies = {};

  void _updateCookies(http.Response response) {
    final setCookie = response.headers['set-cookie'];
    if (setCookie != null) {
      final parts = setCookie.split(',');
      for (var part in parts) {
        var cookieItems = part.split(';');
        if (cookieItems.isNotEmpty) {
          var keyValue = cookieItems[0].split('=');
          if (keyValue.length == 2) {
            cookies[keyValue[0].trim()] = keyValue[1];
          }
        }
      }
    }
  }

  String _getCookieHeader() {
    String cookie = '';
    cookies.forEach((key, value) {
      if (cookie.isNotEmpty) cookie += '; ';
      cookie += '$key=$value';
    });
    return cookie;
  }

  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;
      cookies.clear();
    });

    try {
      final responseGet = await http
          .get(Uri.parse('http://172.16.0.1/status?var=json'))
          .timeout(const Duration(seconds: 10));
      _updateCookies(responseGet);

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

      final responseAfterLogin = await http
          .get(
            Uri.parse('http://172.16.0.1/status?var=json'),
            headers: {'Cookie': _getCookieHeader()},
          )
          .timeout(const Duration(seconds: 10));

      final data = json.decode(responseAfterLogin.body);

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('تسجيل الدخول'), centerTitle: true),
      body: Stack(
        children: [
          Container(
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                colors: [Color(0xFF1565C0), Color(0xFF0D47A1)],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
              ),
            ),
            child: Center(
              child: SingleChildScrollView(
                padding: const EdgeInsets.symmetric(
                  horizontal: 24,
                  vertical: 24,
                ),
                child: Card(
                  elevation: 10,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 28,
                      vertical: 36,
                    ),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(
                          Icons.wifi,
                          size: 100,
                          color: Theme.of(context).primaryColor,
                        ),
                        const SizedBox(height: 24),
                        Text(
                          'مرحباً بك في شبكة الواي فاي',
                          style: const TextStyle(
                            fontSize: 24,
                            fontWeight: FontWeight.bold,
                            fontFamily: 'Tajawal',
                            color: Colors.black87,
                          ),
                          textAlign: TextAlign.center,
                        ),
                        const SizedBox(height: 32),
                        TextField(
                          controller: _usernameController,
                          decoration: const InputDecoration(
                            labelText: 'اسم المستخدم',
                            prefixIcon: Icon(Icons.person),
                          ),
                          style: const TextStyle(fontSize: 18),
                        ),
                        const SizedBox(height: 36),
                        SizedBox(
                          width: double.infinity,
                          child: ElevatedButton(
                            onPressed: _isLoading ? null : _login,
                            child:
                                _isLoading
                                    ? const SizedBox(
                                      width: 24,
                                      height: 24,
                                      child: CircularProgressIndicator(
                                        color: Colors.white,
                                        strokeWidth: 3,
                                      ),
                                    )
                                    : const Text('تسجيل الدخول'),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ),
          if (_showMessage)
            Positioned(
              bottom: 20,
              left: 20,
              right: 20,
              child: AnimatedOpacity(
                opacity: _showMessage ? 1 : 0,
                duration: const Duration(milliseconds: 300),
                child: Material(
                  elevation: 6,
                  borderRadius: BorderRadius.circular(12),
                  color: _isError ? Colors.red[50] : Colors.green[50],
                  child: Container(
                    padding: const EdgeInsets.all(16),
                    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],
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        IconButton(
                          onPressed: () => setState(() => _showMessage = false),
                          icon: const Icon(Icons.close),
                          color: _isError ? Colors.red : Colors.green,
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }
}