import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class LoginController extends GetxController {
  final usernameController = TextEditingController();
  final passwordController = TextEditingController();
  final isPasswordHidden = true.obs;
  final isLoading = false.obs;

  final FirebaseAuth _auth = FirebaseAuth.instance;
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;

  void togglePasswordVisibility() {
    isPasswordHidden.value = !isPasswordHidden.value;
  }

  void login() async {
    if (usernameController.text.isEmpty || passwordController.text.isEmpty) {
      Get.snackbar(
        'Error',
        'Email dan password harus diisi',
        backgroundColor: Colors.red[100],
        colorText: Colors.red[900],
        snackPosition: SnackPosition.TOP,
      );
      return;
    }

    if (!GetUtils.isEmail(usernameController.text)) {
      Get.snackbar(
        'Error',
        'Format email tidak valid',
        backgroundColor: Colors.red[100],
        colorText: Colors.red[900],
        snackPosition: SnackPosition.TOP,
      );
      return;
    }

    try {
      isLoading.value = true;

      UserCredential userCredential = await _auth.signInWithEmailAndPassword(
        email: usernameController.text.trim(),
        password: passwordController.text.trim(),
      );

      if (userCredential.user != null) {
        final userDoc = await _firestore
            .collection('users')
            .doc(userCredential.user!.uid)
            .get();

        if (userDoc.exists) {
          final userData = userDoc.data()!;
          final deviceId = userData['device_id'] as String?;
          final userName = userData['name'] as String? ?? 'User';

          if (deviceId != null && deviceId.isNotEmpty) {
            Get.snackbar(
              'Berhasil',
              'Selamat datang, $userName!',
              backgroundColor: Colors.green[100],
              colorText: Colors.green[900],
              snackPosition: SnackPosition.TOP,
            );

            Get.offAllNamed(
              '/home-patient',
              arguments: {
                'deviceId': deviceId,
                'userName': userName,
                'userEmail': usernameController.text.trim(),
              },
            );
          } else {
            Get.snackbar(
              'Error',
              'Akun Anda belum terdaftar dengan device',
              backgroundColor: Colors.orange[100],
              colorText: Colors.orange[900],
              snackPosition: SnackPosition.TOP,
            );
            await _auth.signOut();
          }
        } else {
          Get.snackbar(
            'Berhasil',
            'Login berhasil! Selamat datang, Perawat',
            backgroundColor: Colors.green[100],
            colorText: Colors.green[900],
            snackPosition: SnackPosition.TOP,
          );

          Get.offAllNamed('/navbar');
        }
      }
    } on FirebaseAuthException catch (e) {
      String errorMessage = '';

      switch (e.code) {
        case 'user-not-found':
          errorMessage = 'Email tidak terdaftar';
          break;
        case 'wrong-password':
          errorMessage = 'Password salah';
          break;
        case 'invalid-email':
          errorMessage = 'Format email tidak valid';
          break;
        case 'user-disabled':
          errorMessage = 'Akun telah dinonaktifkan';
          break;
        case 'too-many-requests':
          errorMessage = 'Terlalu banyak percobaan login. Coba lagi nanti';
          break;
        case 'network-request-failed':
          errorMessage = 'Tidak ada koneksi internet';
          break;
        default:
          errorMessage = 'Terjadi kesalahan: ${e.message}';
      }

      Get.snackbar(
        'Login Gagal',
        errorMessage,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[900],
        snackPosition: SnackPosition.TOP,
        duration: const Duration(seconds: 3),
      );
    } catch (e) {
      Get.snackbar(
        'Error',
        'Terjadi kesalahan: $e',
        backgroundColor: Colors.red[100],
        colorText: Colors.red[900],
        snackPosition: SnackPosition.TOP,
      );
    } finally {
      isLoading.value = false;
    }
  }

  void contactNurse() async {
    const phoneNumber = '6281231901277';
    final message = Uri.encodeComponent(
      'Halo, saya wali pasien dari (Nama Pasien) '
      'Saya ingin meminta akun untuk login ke aplikasi Smart Infus.',
    );

    // Construct the WhatsApp URL with the message
    final url = Uri.parse('https://wa.me/$phoneNumber?text=$message');

    // Attempt to launch WhatsApp
    if (await canLaunchUrl(url)) {
      await launchUrl(url, mode: LaunchMode.externalApplication);
    } else {
      // Show an error if WhatsApp can't be opened
      Get.snackbar(
        'Error',
        'Tidak dapat membuka WhatsApp',
        backgroundColor: Colors.red[100],
        colorText: Colors.red[900],
      );
    }
  }

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