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

import '../controllers/ntrip_settings_controller.dart';

class NtripSettingsSheet extends GetView<NtripSettingsController> {
  const NtripSettingsSheet({super.key});

  static Future<void> show() async {
    Get.put(NtripSettingsController());
    try {
      await Get.bottomSheet(
        const NtripSettingsSheet(),
        isScrollControlled: true,
      );
    } finally {
      Get.delete<NtripSettingsController>();
    }
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;
    final bottomInset = MediaQuery.viewInsetsOf(context).bottom;
    final screenHeight = MediaQuery.sizeOf(context).height;

    return SafeArea(
      top: false,
      child: Align(
        alignment: Alignment.bottomCenter,
        child: ConstrainedBox(
          constraints: BoxConstraints(
            maxHeight: screenHeight * 0.86,
          ),
          child: Material(
            color: colorScheme.surface,
            borderRadius: const BorderRadius.vertical(
              top: Radius.circular(24),
            ),
            clipBehavior: Clip.antiAlias,
            child: SingleChildScrollView(
              keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
              reverse: true,
              padding: EdgeInsets.fromLTRB(16, 12, 16, 20 + bottomInset),
              child: Form(
                key: controller.formKey,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Center(
                      child: Container(
                        width: 42,
                        height: 4,
                        margin: const EdgeInsets.only(bottom: 14),
                        decoration: BoxDecoration(
                          color: colorScheme.outlineVariant,
                          borderRadius: BorderRadius.circular(999),
                        ),
                      ),
                    ),
                    Row(
                      children: [
                        const Icon(Icons.settings_input_antenna),
                        const SizedBox(width: 8),
                        Text(
                          'NTRIP beállítások',
                          style: Theme.of(context).textTheme.titleLarge,
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                    TextFormField(
                      controller: controller.hostController,
                      decoration: const InputDecoration(
                        labelText: 'Caster / host',
                        hintText: 'pl. caster.example.com',
                        prefixIcon: Icon(Icons.dns),
                      ),
                      textInputAction: TextInputAction.next,
                      validator: (value) {
                        if (value == null || value.trim().isEmpty) {
                          return 'A host megadása kötelező.';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 12),
                    TextFormField(
                      controller: controller.portController,
                      decoration: const InputDecoration(
                        labelText: 'Port',
                        hintText: '2101',
                        prefixIcon: Icon(Icons.tag),
                      ),
                      keyboardType: TextInputType.number,
                      textInputAction: TextInputAction.next,
                      validator: (value) {
                        final port = int.tryParse(value?.trim() ?? '');
                        if (port == null || port <= 0 || port > 65535) {
                          return 'Érvényes portszámot adj meg.';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 12),
                    TextFormField(
                      controller: controller.mountPointController,
                      decoration: const InputDecoration(
                        labelText: 'Mountpoint',
                        hintText: 'pl. SGO_RTK3.2',
                        prefixIcon: Icon(Icons.place),
                      ),
                      textInputAction: TextInputAction.next,
                      validator: (value) {
                        if (value == null || value.trim().isEmpty) {
                          return 'A mountpoint megadása kötelező.';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 12),
                    TextFormField(
                      controller: controller.usernameController,
                      decoration: const InputDecoration(
                        labelText: 'Felhasználónév',
                        prefixIcon: Icon(Icons.person),
                      ),
                      textInputAction: TextInputAction.next,
                    ),
                    const SizedBox(height: 12),
                    Obx(() {
                      return TextFormField(
                        controller: controller.passwordController,
                        decoration: InputDecoration(
                          labelText: 'Jelszó',
                          prefixIcon: const Icon(Icons.lock),
                          suffixIcon: IconButton(
                            icon: Icon(
                              controller.isPasswordVisible.value
                                  ? Icons.visibility_off
                                  : Icons.visibility,
                            ),
                            onPressed: () {
                              controller.isPasswordVisible.value =
                                  !controller.isPasswordVisible.value;
                            },
                          ),
                        ),
                        obscureText: !controller.isPasswordVisible.value,
                      );
                    }),
                    const SizedBox(height: 8),
                    Obx(() {
                      return SwitchListTile(
                        contentPadding: EdgeInsets.zero,
                        title: const Text('Automatikus kapcsolódás'),
                        subtitle: const Text(
                          'RTK képes vevő csatlakozásakor próbáljon automatikusan NTRIP-re kapcsolódni.',
                        ),
                        value: controller.autoConnect.value,
                        onChanged: (value) {
                          controller.autoConnect.value = value;
                        },
                      );
                    }),
                    const SizedBox(height: 16),
                    Obx(() {
                      final isBusy = controller.isBusy.value;
                      final isConnected = NtripService.to.isConnected.value;

                      return Row(
                        children: [
                          if (isConnected)
                            Expanded(
                              child: OutlinedButton.icon(
                                onPressed:
                                    isBusy ? null : controller.disconnect,
                                icon: const Icon(Icons.link_off),
                                label: const Text('Bontás'),
                              ),
                            ),
                          if (isConnected) const SizedBox(width: 12),
                          Expanded(
                            child: FilledButton.icon(
                              onPressed:
                                  isBusy ? null : controller.saveAndConnect,
                              icon: isBusy
                                  ? const SizedBox(
                                      width: 18,
                                      height: 18,
                                      child: CircularProgressIndicator(
                                        strokeWidth: 2,
                                      ),
                                    )
                                  : const Icon(Icons.play_arrow),
                              label: Text(
                                isBusy
                                    ? 'Kapcsolódás...'
                                    : 'Mentés és kapcsolódás',
                              ),
                            ),
                          ),
                        ],
                      );
                    }),
                    const SizedBox(height: 8),
                    SizedBox(
                      width: double.infinity,
                      child: TextButton(
                        onPressed: () async {
                          await controller.saveSettings();
                          Get.back();
                        },
                        child: const Text('Csak mentés'),
                      ),
                    ),
                    SizedBox(
                        width: double.infinity,
                        child: Obx(() => OutlinedButton.icon(
                            onPressed: controller.isBusy.value
                                ? null
                                : controller.testConnection,
                            icon: const Icon(Icons.network_check, size: 18),
                            label: const Text(
                                'Kapcsolat tesztelése (vevő nélkül)'))))
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
