import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../services/auth_service.dart';
import '../services/api_service.dart';
import '../home/home_screen.dart';

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

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

class _LoginScreenState extends State<LoginScreen> {
  final _usernameCtrl = TextEditingController();
  final _secretCtrl = TextEditingController();
  final _authService = AuthService();
  late final ApiService _api;
  bool _loading = false;
  String? _error;

  // کانال ارتباطی با کد نیتیو برای تنظیمات اینترنت
  static final _nativeChannel = const MethodChannel(
    'com.example.watch/launcher',
  );

  @override
  void initState() {
    super.initState();
    _api = ApiService(_authService);
  }

  @override
  void dispose() {
    _usernameCtrl.dispose();
    _secretCtrl.dispose();
    super.dispose();
  }

  // متد باز کردن تنظیمات اینترنت
  Future<void> _openInternetSettings() async {
    try {
      await _nativeChannel.invokeMethod('openInternetSettings');
    } catch (_) {
      _showSnack('تنظیمات اینترنت در دسترس نیست');
    }
  }

  // متد نمایش پیام (SnackBar)
  void _showSnack(String msg) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
          msg,
          style: const TextStyle(fontSize: 10, color: Colors.white),
        ),
        backgroundColor: const Color(0xFF2C2C2E),
        duration: const Duration(seconds: 2),
        behavior: SnackBarBehavior.floating,
        margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 40),
      ),
    );
  }

  Future<void> _login() async {
    final username = _usernameCtrl.text.trim();
    final secret = _secretCtrl.text.trim();
    if (username.isEmpty || secret.isEmpty) {
      setState(() => _error = 'نام کاربری و کلید را وارد کنید');
      return;
    }
    setState(() {
      _loading = true;
      _error = null;
    });

    final ok = await _api.login(username, secret);
    if (!mounted) return;

    if (ok) {
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (_) => const HomeScreen()),
      );
    } else {
      setState(() {
        _loading = false;
        _error = 'نام کاربری یا کلید نادرست است';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: SingleChildScrollView(
          child: ConstrainedBox(
            constraints: BoxConstraints(
              minHeight:
                  MediaQuery.of(context).size.height -
                  MediaQuery.of(context).padding.top -
                  MediaQuery.of(context).padding.bottom,
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // محتوای اصلی فرم
                Padding(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 20,
                    vertical: 8,
                  ),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      // Icon
                      Container(
                        width: 36,
                        height: 36,
                        decoration: BoxDecoration(
                          color: const Color(0xFF00C853).withOpacity(0.15),
                          shape: BoxShape.circle,
                        ),
                        child: const Icon(
                          Icons.settings_input_antenna,
                          color: Color(0xFF00C853),
                          size: 18,
                        ),
                      ),
                      const SizedBox(height: 4),
                      const Text(
                        'WalkieTalkie',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 12,
                          fontWeight: FontWeight.bold,
                          letterSpacing: 1,
                        ),
                      ),
                      const SizedBox(height: 10),

                      // Username input
                      SizedBox(
                        height: 32,
                        child: TextField(
                          controller: _usernameCtrl,
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 11,
                          ),
                          textAlign: TextAlign.center,
                          decoration: InputDecoration(
                            hintText: 'نام کاربری',
                            hintStyle: const TextStyle(
                              color: Colors.white38,
                              fontSize: 10,
                            ),
                            filled: true,
                            fillColor: const Color(0xFF1C1C1E),
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(16),
                              borderSide: BorderSide.none,
                            ),
                            contentPadding: const EdgeInsets.symmetric(
                              horizontal: 10,
                              vertical: 0,
                            ),
                          ),
                          onSubmitted: (_) =>
                              FocusScope.of(context).nextFocus(),
                        ),
                      ),
                      const SizedBox(height: 6),

                      // Secret input
                      SizedBox(
                        height: 32,
                        child: TextField(
                          controller: _secretCtrl,
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 11,
                          ),
                          textAlign: TextAlign.center,
                          obscureText: true,
                          decoration: InputDecoration(
                            hintText: 'کلید ورود',
                            hintStyle: const TextStyle(
                              color: Colors.white38,
                              fontSize: 10,
                            ),
                            filled: true,
                            fillColor: const Color(0xFF1C1C1E),
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(16),
                              borderSide: BorderSide.none,
                            ),
                            contentPadding: const EdgeInsets.symmetric(
                              horizontal: 10,
                              vertical: 0,
                            ),
                          ),
                          onSubmitted: (_) => _login(),
                        ),
                      ),

                      // Error
                      SizedBox(
                        height: 16,
                        child: _error != null
                            ? Text(
                                _error!,
                                style: const TextStyle(
                                  color: Color(0xFFFF1744),
                                  fontSize: 9,
                                ),
                              )
                            : null,
                      ),

                      // Login button
                      GestureDetector(
                        onTap: _loading ? null : _login,
                        child: AnimatedContainer(
                          duration: const Duration(milliseconds: 200),
                          width: 50,
                          height: 50,
                          decoration: BoxDecoration(
                            color: _loading
                                ? const Color(0xFF424242)
                                : const Color(0xFF00C853),
                            shape: BoxShape.circle,
                            boxShadow: _loading
                                ? null
                                : [
                                    BoxShadow(
                                      color: const Color(
                                        0xFF00C853,
                                      ).withOpacity(0.4),
                                      blurRadius: 10,
                                      spreadRadius: 1,
                                    ),
                                  ],
                          ),
                          child: _loading
                              ? const Center(
                                  child: SizedBox(
                                    width: 18,
                                    height: 18,
                                    child: CircularProgressIndicator(
                                      color: Colors.white,
                                      strokeWidth: 2,
                                    ),
                                  ),
                                )
                              : const Icon(
                                  Icons.login,
                                  color: Colors.white,
                                  size: 22,
                                ),
                        ),
                      ),
                      const SizedBox(height: 4),
                      const Text(
                        'ورود',
                        style: TextStyle(color: Colors.white38, fontSize: 9),
                      ),
                    ],
                  ),
                ),

                const SizedBox(height: 20),

                // دکمه تنظیمات اینترنت (پایین صفحه وسط)
                GestureDetector(
                  onTap: _openInternetSettings,
                  child: Container(
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      color: const Color(0xFF1C1C1E),
                      shape: BoxShape.circle,
                      border: Border.all(
                        color: const Color(0xFF00BCD4).withOpacity(0.3),
                        width: 1,
                      ),
                    ),
                    child: const Icon(
                      Icons.wifi,
                      color: Color(0xFF00BCD4),
                      size: 20,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
