import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:get/get.dart';
import 'package:terepi_seged/services/ntrip_service.dart';
import 'package:shared_preferences/shared_preferences.dart';

class NtripSettingsController extends GetxController {
  final formKey = GlobalKey<FormState>();

  final hostController = TextEditingController();
  final portController = TextEditingController();
  final mountPointController = TextEditingController();
  final usernameController = TextEditingController();
  final passwordController = TextEditingController();

  final isPasswordVisible = false.obs;
  final autoConnect = false.obs;
  final isBusy = false.obs;

  NtripService get _service => NtripService.to;

  @override
  void onInit() {
    super.onInit();
    loadSettings();
  }

  Future<void> loadSettings() async {
    hostController.text = _service.host.value;
    portController.text = _service.port.value.toString();
    mountPointController.text = _service.mountpoint.value;
    usernameController.text = _service.username.value;
    autoConnect.value = _service.autoConnect.value;
    passwordController.text = _service.password.value;
  }

  Future<bool> _validateAndSave() async {
    if (!(formKey.currentState?.validate() ?? false)) return false;

    await _service.updateSettings(
        host: hostController.text,
        port: int.parse(portController.text.trim()),
        mountpoint: mountPointController.text,
        username: usernameController.text,
        password: passwordController.text,
        autoConnect: autoConnect.value);
    return true;
  }

  Future<void> saveSettings() async {
    if (!await _validateAndSave()) return;

    Get.back();
    Get.snackbar('NTRIP', 'Beállítások elmentve.',
        snackPosition: SnackPosition.BOTTOM);
  }

  Future<void> saveAndConnect() async {
    try {
      isBusy.value = true;

      if (!await _validateAndSave()) return;

      // Ha már kapcsolódva vagyunk, előbb bontunk, hogy az új
      // beállításokkal épüljön újra a kapcsolat.
      if (_service.isConnected.value) {
        await _service.disconnect();
      }

      await _service.connect();

      Get.back();
      Get.snackbar(
        'NTRIP',
        'Kapcsolódva: ${_service.mountpoint.value}',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: const Color(0xFF2E7D32),
        colorText: const Color(0xFFFFFFFF),
      );
    } on NtripException catch (e) {
      Get.snackbar(
        'NTRIP hiba',
        e.message,
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: const Color(0xFFB71C1C),
        colorText: const Color(0xFFFFFFFF),
      );
    } catch (e) {
      Get.snackbar(
        'NTRIP hiba',
        e.toString(),
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: const Color(0xFFB71C1C),
        colorText: const Color(0xFFFFFFFF),
      );
    } finally {
      isBusy.value = false;
    }
  }

  Future<void> disconnect() async {
    try {
      isBusy.value = true;
      await _service.disconnect();
    } finally {
      isBusy.value = false;
    }
  }

  @override
  void onClose() {
    hostController.dispose();
    portController.dispose();
    mountPointController.dispose();
    usernameController.dispose();
    passwordController.dispose();
    super.onClose();
  }

  /// „Kapcsolat tesztelése" — vevő nélkül is fut: mentés után csatlakozik,
  /// validálja a caster válaszát, majd azonnal bont.
  Future<void> testConnection() async {
    try {
      isBusy.value = true;
      if (!await _validateAndSave()) return;

      final message = await _service.testConnection();
      Get.snackbar(
        'NTRIP teszt sikeres',
        message,
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: const Color(0xFF2E7D32),
        colorText: const Color(0xFFFFFFFF),
        duration: const Duration(seconds: 4),
      );
    } on NtripException catch (e) {
      Get.snackbar(
        'NTRIP teszt sikertelen',
        e.message,
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: const Color(0xFFB71C1C),
        colorText: const Color(0xFFFFFFFF),
        duration: const Duration(seconds: 4),
      );
    } catch (e) {
      Get.snackbar(
        'NTRIP teszt sikertelen',
        e.toString(),
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: const Color(0xFFB71C1C),
        colorText: const Color(0xFFFFFFFF),
      );
    } finally {
      isBusy.value = false;
    }
  }
}
