import 'dart:convert';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

class LoginPage extends StatefulWidget {
  final bool fromGuard;

  const LoginPage({
    super.key,
    this.fromGuard = false,
  });

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  final TextEditingController _forgotEmailController = TextEditingController();
  final TextEditingController _otpController = TextEditingController();
  final TextEditingController _newPasswordController = TextEditingController();

  bool _isPasswordHidden = true;
  bool _isNewPasswordHidden = true;
  bool _isLoading = false;

  String? _loginErrorMessage;
  String? _dialogErrorMessage;

  // Sesuaikan baseUrl jika menggunakan HP fisik (gunakan IP Laptop)
  static const String baseUrl = "http://ta.myhost.id/E31230549/mposyandu_api";

  final String loginUrl = "$baseUrl/login.php";
  final String forgotPasswordUrl = "$baseUrl/forgot_password.php";
  final String resetPasswordUrl = "$baseUrl/reset_password.php";

  @override
  void initState() {
    super.initState();
    if (widget.fromGuard) {
      _loginErrorMessage = "Anda harus login terlebih dahulu";
    }
  }

  // ================= LOGIN FUNCTION (PERBAIKAN LOGIKA NIK & SHOWDIALOG) =================
  Future<void> _login() async {
    final email = _emailController.text.trim();
    final password = _passwordController.text.trim();

    setState(() => _loginErrorMessage = null);

    if (email.isEmpty || password.isEmpty) {
      setState(() => _loginErrorMessage = "Email dan password wajib diisi");
      return;
    }

    setState(() => _isLoading = true);

    try {
      log("Memulai proses login untuk: $email");

      final response = await http.post(
        Uri.parse(loginUrl),
        body: {"email": email, "password": password},
      ).timeout(const Duration(seconds: 10));

      log("Response Server: ${response.body}");

      if (response.statusCode == 200) {
        final data = json.decode(response.body);

        if (data["success"] == true) {
          final prefs = await SharedPreferences.getInstance();
          final Map<String, dynamic> user = data["user"];

          // 1. Simpan Status Login
          await prefs.setBool("isLogin", true);

          // 2. Simpan password yang diketik untuk pengecekan showDialog di Dashboard Ibu
          await prefs.setString("last_entered_password", password);

          // 3. Simpan semua data user secara dinamis
          List<Future<bool>> saves = [];
          user.forEach((key, value) {
            saves.add(prefs.setString(key, value?.toString() ?? ""));
          });

          // 4. Pastikan id_user tersimpan (Dashboard sering mencari key ini)
          if (user.containsKey("id")) {
            saves.add(prefs.setString("id_user", user["id"].toString()));
          }

          // 5. Pastikan NIK tersimpan (Penting untuk perbandingan password default)
          if (user.containsKey("nik")) {
            saves.add(prefs.setString("nik", user["nik"].toString()));
          }

          await Future.wait(saves);

          if (!mounted) return;

          String role = user["role"] ?? "";
          switch (role.toLowerCase()) {
            case "admin":
              Navigator.pushReplacementNamed(context, '/dashboard-admin');
              break;
            case "kader":
              Navigator.pushReplacementNamed(context, '/dashboard-kader');
              break;
            case "bidan":
              Navigator.pushReplacementNamed(context, '/dashboard-bidan');
              break;
            case "ibu":
              Navigator.pushReplacementNamed(context, '/dashboard-ibu');
              break;
            default:
              setState(() => _loginErrorMessage = "Role tidak dikenali");
          }
        } else {
          setState(() => _loginErrorMessage = data["message"] ?? "Login gagal");
        }
      } else {
        setState(
            () => _loginErrorMessage = "Server error: ${response.statusCode}");
      }
    } catch (e) {
      log("Error Login: $e");
      setState(() => _loginErrorMessage = "Gagal terhubung ke server.");
    } finally {
      if (mounted) setState(() => _isLoading = false);
    }
  }

  // ================= FORGOT PASSWORD FUNCTIONS (TETAP SAMA) =================

  Future<void> _sendOtp(StateSetter setDialogState) async {
    final email = _forgotEmailController.text.trim();
    setDialogState(() => _dialogErrorMessage = null);

    if (email.isEmpty) {
      setDialogState(() => _dialogErrorMessage = "Masukkan email Anda");
      return;
    }

    _showLoadingDialog();

    try {
      final response = await http.post(
        Uri.parse(forgotPasswordUrl),
        body: {"email": email},
      ).timeout(const Duration(seconds: 20));

      if (!mounted) return;
      Navigator.pop(context);

      final data = json.decode(response.body);
      if (data["success"] == true) {
        Navigator.pop(context);
        _showOtpDialog();
      } else {
        setDialogState(() =>
            _dialogErrorMessage = data["message"] ?? "Email tidak ditemukan");
      }
    } catch (e) {
      if (mounted) Navigator.pop(context);
      setDialogState(
          () => _dialogErrorMessage = "Kesalahan koneksi: Gagal mengirim OTP");
    }
  }

  Future<void> _resetPassword(StateSetter setDialogState) async {
    final email = _forgotEmailController.text.trim();
    final otp = _otpController.text.trim();
    final newPass = _newPasswordController.text.trim();

    setDialogState(() => _dialogErrorMessage = null);

    if (otp.isEmpty || newPass.isEmpty) {
      setDialogState(() => _dialogErrorMessage = "Lengkapi semua field");
      return;
    }

    final hasLetter = RegExp(r'[a-zA-Z]').hasMatch(newPass);
    final hasDigit = RegExp(r'[0-9]').hasMatch(newPass);

    if (newPass.length != 6 || !hasLetter || !hasDigit) {
      setDialogState(
          () => _dialogErrorMessage = "Gunakan 6 karakter (huruf & angka)");
      return;
    }

    _showLoadingDialog();

    try {
      final response = await http.post(
        Uri.parse(resetPasswordUrl),
        body: {
          "email": email,
          "otp": otp,
          "new_password": newPass,
        },
      ).timeout(const Duration(seconds: 15));

      if (!mounted) return;
      Navigator.pop(context);

      final data = json.decode(response.body);
      if (data["success"] == true) {
        Navigator.pop(context);
        _showMessage("Password berhasil direset!");
        _clearForgotControllers();
      } else {
        setDialogState(
            () => _dialogErrorMessage = data["message"] ?? "OTP salah");
      }
    } catch (e) {
      if (mounted) Navigator.pop(context);
      setDialogState(() => _dialogErrorMessage = "Gagal mereset password");
    }
  }

  // ================= DIALOGS & UI HELPERS (TETAP SAMA) =================

  void _showForgotPasswordDialog() {
    _dialogErrorMessage = null;
    showDialog(
      context: context,
      builder: (context) => StatefulBuilder(builder: (context, setDialogState) {
        return AlertDialog(
          backgroundColor: Colors.white,
          surfaceTintColor: Colors.white,
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
          title: Text("Lupa Password",
              style: GoogleFonts.poppins(
                  fontWeight: FontWeight.bold, color: Colors.black)),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TextField(
                controller: _forgotEmailController,
                decoration: InputDecoration(
                  hintText: "Email terdaftar",
                  prefixIcon: const Icon(Icons.email, color: Colors.blue),
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10)),
                ),
                keyboardType: TextInputType.emailAddress,
              ),
              if (_dialogErrorMessage != null)
                Padding(
                  padding: const EdgeInsets.only(top: 8, left: 4),
                  child: Text(_dialogErrorMessage!,
                      style:
                          GoogleFonts.poppins(color: Colors.red, fontSize: 12)),
                ),
            ],
          ),
          actions: [
            OutlinedButton(
              onPressed: () => Navigator.pop(context),
              style: OutlinedButton.styleFrom(
                side: const BorderSide(color: Colors.red),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8)),
              ),
              child:
                  Text("Batal", style: GoogleFonts.poppins(color: Colors.red)),
            ),
            OutlinedButton(
              onPressed: () => _sendOtp(setDialogState),
              style: OutlinedButton.styleFrom(
                side: const BorderSide(color: Colors.blue),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8)),
              ),
              child: Text("Kirim OTP",
                  style: GoogleFonts.poppins(color: Colors.blue)),
            ),
          ],
        );
      }),
    );
  }

  void _showOtpDialog() {
    _dialogErrorMessage = null;
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => StatefulBuilder(
        builder: (context, setDialogState) {
          return AlertDialog(
            backgroundColor: Colors.white,
            surfaceTintColor: Colors.white,
            shape:
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
            title: Text("Verifikasi OTP",
                style: GoogleFonts.poppins(
                    fontWeight: FontWeight.bold, color: Colors.black)),
            content: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text("Masukkan kode OTP dan password baru",
                      style: GoogleFonts.poppins(fontSize: 12)),
                  const SizedBox(height: 15),
                  TextField(
                    controller: _otpController,
                    decoration: InputDecoration(
                        labelText: "Kode OTP",
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10))),
                    keyboardType: TextInputType.number,
                  ),
                  const SizedBox(height: 15),
                  TextField(
                    controller: _newPasswordController,
                    obscureText: _isNewPasswordHidden,
                    inputFormatters: [
                      LengthLimitingTextInputFormatter(6),
                      FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9]')),
                    ],
                    decoration: InputDecoration(
                      labelText: "Password Baru (6 Karakter)",
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10)),
                      suffixIcon: IconButton(
                        icon: Icon(_isNewPasswordHidden
                            ? Icons.visibility
                            : Icons.visibility_off),
                        onPressed: () => setDialogState(
                            () => _isNewPasswordHidden = !_isNewPasswordHidden),
                      ),
                    ),
                  ),
                  if (_dialogErrorMessage != null)
                    Padding(
                      padding: const EdgeInsets.only(top: 8, left: 4),
                      child: Text(_dialogErrorMessage!,
                          style: GoogleFonts.poppins(
                              color: Colors.red, fontSize: 12)),
                    ),
                ],
              ),
            ),
            actions: [
              OutlinedButton(
                onPressed: () => Navigator.pop(context),
                style: OutlinedButton.styleFrom(
                  side: const BorderSide(color: Colors.red),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8)),
                ),
                child: Text("Batal",
                    style: GoogleFonts.poppins(color: Colors.red)),
              ),
              OutlinedButton(
                onPressed: () => _resetPassword(setDialogState),
                style: OutlinedButton.styleFrom(
                  side: const BorderSide(color: Colors.blue),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8)),
                ),
                child: Text("Simpan",
                    style: GoogleFonts.poppins(color: Colors.blue)),
              ),
            ],
          );
        },
      ),
    );
  }

  void _showLoadingDialog() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const Center(child: CircularProgressIndicator()),
    );
  }

  void _showMessage(String msg) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(msg, style: GoogleFonts.poppins()),
        backgroundColor: Colors.green,
        behavior: SnackBarBehavior.floating,
      ),
    );
  }

  void _clearForgotControllers() {
    _forgotEmailController.clear();
    _otpController.clear();
    _newPasswordController.clear();
    _isNewPasswordHidden = true;
    _dialogErrorMessage = null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: Center(
          child: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(24),
              child: Column(
                children: [
                  const SizedBox(height: 20),
                  Text("M-Posyandu",
                      style: GoogleFonts.poppins(
                          fontSize: 26, fontWeight: FontWeight.w700)),
                  const SizedBox(height: 30),
                  SizedBox(
                    width: 300,
                    child: Image.asset("assets/images/logoo.webp",
                        fit: BoxFit.contain,
                        errorBuilder: (c, e, s) =>
                            const Icon(Icons.image, size: 100)),
                  ),
                  const SizedBox(height: 30),
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Text("Selamat Datang Ayo Login Sekarang",
                        style: GoogleFonts.poppins(
                            fontSize: 18, fontWeight: FontWeight.w600)),
                  ),
                  const SizedBox(height: 20),
                  TextField(
                    controller: _emailController,
                    decoration: InputDecoration(
                      labelText: "Email",
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(15)),
                    ),
                    keyboardType: TextInputType.emailAddress,
                  ),
                  const SizedBox(height: 15),
                  TextField(
                    controller: _passwordController,
                    obscureText: _isPasswordHidden,
                    decoration: InputDecoration(
                      labelText: "Password",
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(15)),
                      suffixIcon: IconButton(
                        icon: Icon(_isPasswordHidden
                            ? Icons.visibility
                            : Icons.visibility_off),
                        onPressed: () => setState(
                            () => _isPasswordHidden = !_isPasswordHidden),
                      ),
                    ),
                  ),
                  if (_loginErrorMessage != null)
                    Align(
                      alignment: Alignment.centerLeft,
                      child: Padding(
                        padding: const EdgeInsets.only(top: 8, left: 4),
                        child: Text(_loginErrorMessage!,
                            style: GoogleFonts.poppins(
                                color: Colors.red,
                                fontSize: 13,
                                fontWeight: FontWeight.w500)),
                      ),
                    ),
                  Align(
                    alignment: Alignment.centerRight,
                    child: TextButton(
                      onPressed: _showForgotPasswordDialog,
                      child: Text("Lupa Password?",
                          style: GoogleFonts.poppins(
                              color: Colors.blue, fontWeight: FontWeight.w500)),
                    ),
                  ),
                  const SizedBox(height: 10),
                  SizedBox(
                    width: double.infinity,
                    height: 50,
                    child: ElevatedButton(
                      onPressed: _isLoading ? null : _login,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.blue,
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10)),
                      ),
                      child: _isLoading
                          ? const CircularProgressIndicator(color: Colors.white)
                          : Text("LOGIN",
                              style: GoogleFonts.poppins(
                                  color: Colors.white,
                                  fontSize: 16,
                                  fontWeight: FontWeight.w600)),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
