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 {
    // Validasi input
    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;
    }

    // Validasi format email
    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;

      // Login dengan Firebase Authentication
      UserCredential userCredential = await _auth.signInWithEmailAndPassword(
        email: usernameController.text.trim(),
        password: passwordController.text.trim(),
      );

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

        if (userDoc.exists) {
          // User ada di collection users (Guardian/Patient)
          final userData = userDoc.data()!;
          final deviceId = userData['device_id'] as String?;
          final userName = userData['name'] as String? ?? 'User';

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

            // Navigasi ke home_patient dengan device_id
            Get.offAllNamed(
              '/home-patient',
              arguments: {
                'deviceId': deviceId,
                'userName': userName,
                'userEmail': usernameController.text.trim(),
              },
            );
          } else {
            // User ada tapi tidak punya device_id
            Get.snackbar(
              'Error',
              'Akun Anda belum terdaftar dengan device',
              backgroundColor: Colors.orange[100],
              colorText: Colors.orange[900],
              snackPosition: SnackPosition.TOP,
            );
            await _auth.signOut();
          }
        } else {
          // User TIDAK ada di collection users = Perawat/Admin
          Get.snackbar(
            'Berhasil',
            'Login berhasil! Selamat datang, Perawat',
            backgroundColor: Colors.green[100],
            colorText: Colors.green[900],
            snackPosition: SnackPosition.TOP,
          );

          // Navigasi ke navbar/home perawat
          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'; // Tanpa spasi
    final url = Uri.parse('https://wa.me/$phoneNumber');

    if (await canLaunchUrl(url)) {
      await launchUrl(url, mode: LaunchMode.externalApplication);
    } else {
      Get.snackbar(
        'Error',
        'Tidak dapat membuka WhatsApp',
        backgroundColor: Colors.red[100],
        colorText: Colors.red[900],
      );
    }
  }

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