import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

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

  @override
  State<WifiScreen> createState() => _WifiScreenState();
}

class _WifiScreenState extends State<WifiScreen> {
  static final _channel = const MethodChannel('com.example.watch/launcher');

  List<Map<String, dynamic>> _networks = [];
  bool _loading = true;
  String? _error;

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

  Future<void> _scan() async {
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final raw = await _channel.invokeListMethod<Object>('getWifiList');
      if (!mounted) return;
      setState(() {
        _networks = (raw ?? [])
            .map((e) => Map<String, dynamic>.from(e as Map))
            .toList();
        _loading = false;
        if (_networks.isEmpty) _error = 'شبکه‌ای یافت نشد';
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loading = false;
        _error = 'خطا در اسکن وای‌فای';
      });
    }
  }

  Future<void> _openWifiSettings() async {
    try {
      await _channel.invokeMethod('openWifiSettings');
    } catch (_) {}
  }

  Future<void> _connectOrSuggest(String ssid, String password) async {
    try {
      final ok = await _channel.invokeMethod<bool>(
        'connectToWifi',
        {'ssid': ssid, 'password': password},
      );
      if (!mounted) return;
      if (ok == true) {
        _showSnack('درخواست اتصال به "$ssid" ارسال شد');
      } else {
        _openWifiSettings();
      }
    } catch (_) {
      _openWifiSettings();
    }
  }

  void _showSnack(String msg) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Text(msg,
          style: const TextStyle(fontSize: 10, color: Colors.white),
          textAlign: TextAlign.center),
      backgroundColor: const Color(0xFF2C2C2E),
      behavior: SnackBarBehavior.floating,
      duration: const Duration(seconds: 2),
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 40),
    ));
  }

  int _bars(int level) {
    if (level >= -50) return 3;
    if (level >= -70) return 2;
    return 1;
  }

  IconData _wifiIcon(int bars) {
    if (bars >= 3) return Icons.wifi;
    if (bars == 2) return Icons.wifi_2_bar;
    return Icons.wifi_1_bar;
  }

  void _onNetworkTap(String ssid, bool secured) {
    if (secured) {
      _showPasswordDialog(ssid);
    } else {
      _connectOrSuggest(ssid, '');
    }
  }

  void _showPasswordDialog(String ssid) async {
    String password = '';
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (ctx) => AlertDialog(
        backgroundColor: const Color(0xFF1C1C1E),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        contentPadding: const EdgeInsets.all(14),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.wifi_password, color: Color(0xFF00C853), size: 22),
            const SizedBox(height: 6),
            Text(ssid,
                style: const TextStyle(
                    color: Colors.white,
                    fontSize: 11,
                    fontWeight: FontWeight.bold),
                textAlign: TextAlign.center),
            const SizedBox(height: 10),
            TextField(
              autofocus: true,
              obscureText: true,
              textAlign: TextAlign.center,
              style: const TextStyle(color: Colors.white, fontSize: 11),
              decoration: InputDecoration(
                hintText: 'رمز عبور',
                hintStyle:
                    const TextStyle(color: Colors.white38, fontSize: 10),
                filled: true,
                fillColor: Colors.white.withValues(alpha: 0.05),
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                    borderSide: BorderSide.none),
                contentPadding:
                    const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              ),
              onChanged: (v) => password = v,
            ),
            const SizedBox(height: 10),
            Row(
              children: [
                Expanded(
                  child: TextButton(
                    onPressed: () => Navigator.pop(ctx, false),
                    child: const Text('انصراف',
                        style:
                            TextStyle(color: Colors.white54, fontSize: 11)),
                  ),
                ),
                Expanded(
                  child: TextButton(
                    onPressed: () => Navigator.pop(ctx, true),
                    child: const Text('اتصال',
                        style: TextStyle(
                            color: Color(0xFF00C853),
                            fontSize: 11,
                            fontWeight: FontWeight.bold)),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
    if (confirmed == true && password.isNotEmpty) {
      _connectOrSuggest(ssid, password);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Column(
          children: [
            // Header
            Padding(
              padding:
                  const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  GestureDetector(
                    onTap: () => Navigator.pop(context),
                    child: const Icon(Icons.arrow_back_ios_new,
                        color: Colors.white54, size: 14),
                  ),
                  const SizedBox(width: 6),
                  const Icon(Icons.wifi, color: Color(0xFF00C853), size: 14),
                  const SizedBox(width: 6),
                  const Text('وای‌فای',
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 13,
                          fontWeight: FontWeight.bold)),
                  const SizedBox(width: 8),
                  GestureDetector(
                    onTap: _loading ? null : _scan,
                    child: Icon(Icons.refresh,
                        color: _loading ? Colors.white24 : Colors.white54,
                        size: 14),
                  ),
                ],
              ),
            ),

            // Content
            Expanded(
              child: _loading
                  ? const Center(
                      child: CircularProgressIndicator(
                          color: Color(0xFF00C853), strokeWidth: 2))
                  : _error != null && _networks.isEmpty
                      ? Center(
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              const Icon(Icons.wifi_off,
                                  color: Colors.white38, size: 24),
                              const SizedBox(height: 6),
                              Text(_error!,
                                  style: const TextStyle(
                                      color: Colors.white38, fontSize: 11)),
                              const SizedBox(height: 10),
                              GestureDetector(
                                onTap: _openWifiSettings,
                                child: Container(
                                  padding: const EdgeInsets.symmetric(
                                      horizontal: 14, vertical: 6),
                                  decoration: BoxDecoration(
                                    color: const Color(0xFF1C1C1E),
                                    borderRadius: BorderRadius.circular(12),
                                  ),
                                  child: const Text('تنظیمات وای‌فای',
                                      style: TextStyle(
                                          color: Color(0xFF00C853),
                                          fontSize: 10)),
                                ),
                              ),
                            ],
                          ),
                        )
                      : ListView.builder(
                          padding: const EdgeInsets.only(bottom: 4),
                          itemCount: _networks.length + 1,
                          itemBuilder: (ctx, i) {
                            // Last item: settings link
                            if (i == _networks.length) {
                              return Padding(
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 8, vertical: 3),
                                child: GestureDetector(
                                  onTap: _openWifiSettings,
                                  child: Container(
                                    height: 34,
                                    decoration: BoxDecoration(
                                      color: const Color(0xFF1C1C1E),
                                      borderRadius:
                                          BorderRadius.circular(12),
                                    ),
                                    child: const Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        Icon(Icons.settings,
                                            size: 12,
                                            color: Colors.white38),
                                        SizedBox(width: 4),
                                        Text('تنظیمات وای‌فای',
                                            style: TextStyle(
                                                color: Colors.white38,
                                                fontSize: 10)),
                                      ],
                                    ),
                                  ),
                                ),
                              );
                            }

                            final net = _networks[i];
                            final ssid = (net['ssid'] as String?) ?? '';
                            final level = (net['level'] as int?) ?? -100;
                            final secured =
                                (net['secured'] as bool?) ?? false;
                            final bars = _bars(level);

                            return GestureDetector(
                              onTap: () => _onNetworkTap(ssid, secured),
                              child: Container(
                                margin: const EdgeInsets.symmetric(
                                    horizontal: 8, vertical: 2),
                                height: 40,
                                decoration: BoxDecoration(
                                  color: const Color(0xFF1C1C1E),
                                  borderRadius: BorderRadius.circular(12),
                                ),
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 10),
                                child: Row(
                                  children: [
                                    Icon(_wifiIcon(bars),
                                        color: const Color(0xFF00C853),
                                        size: 14),
                                    const SizedBox(width: 8),
                                    Expanded(
                                      child: Text(
                                        ssid,
                                        style: const TextStyle(
                                            color: Colors.white,
                                            fontSize: 11),
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                    if (secured)
                                      const Icon(Icons.lock_outline,
                                          color: Colors.white38, size: 10),
                                  ],
                                ),
                              ),
                            );
                          },
                        ),
            ),
          ],
        ),
      ),
    );
  }
}
