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

import 'login_page.dart';

class RegisterPage extends StatefulWidget {
  const RegisterPage({super.key});

  @override
  State<RegisterPage> createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  // ================= CONTROLLER =================
  final TextEditingController namaController = TextEditingController();
  final TextEditingController emailController = TextEditingController();
  final TextEditingController noHpController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();
  final TextEditingController nikController = TextEditingController();

  // ================= DROPDOWN DATA =================
  List desaList = [];
  List dusunList = [];

  String? selectedDesaId;
  String? selectedDusunId;

  final String baseUrl = "http://ta.myhost.id/E31230549/mposyandu_api";

  // ================= INIT =================
  @override
  void initState() {
    super.initState();
    fetchDesa();
  }

  // ================= FETCH DESA =================
  Future<void> fetchDesa() async {
    try {
      var url = Uri.parse("$baseUrl/desa/get_desa.php");
      var response = await http.get(url);

      debugPrint("DESA RAW: ${response.body}");

      var jsonData = json.decode(response.body);

      if (mounted) {
        setState(() {
          desaList = jsonData["data"] ?? [];
        });
      }
    } catch (e) {
      debugPrint("ERROR DESA: $e");
    }
  }

  // ================= FETCH DUSUN (FIXED) =================
  Future<void> fetchDusun(String desaId) async {
    try {
      debugPrint("FETCH DUSUN desa_id: $desaId");

      var url = Uri.parse("$baseUrl/dusun/get_dusun.php?desa_id=$desaId");
      var response = await http.get(url);

      debugPrint("DUSUN RAW: ${response.body}");

      var jsonData = json.decode(response.body);

      // ✅ samakan pola dengan desa + safe parsing
      List tempList = [];

      if (jsonData is Map && jsonData["data"] != null) {
        tempList = jsonData["data"];
      } else if (jsonData is List) {
        // kalau API langsung return array
        tempList = jsonData;
      }

      if (mounted) {
        setState(() {
          dusunList = tempList;
          selectedDusunId = null;
        });
      }

      debugPrint("DUSUN COUNT: ${dusunList.length}");
    } catch (e) {
      debugPrint("ERROR DUSUN: $e");
    }
  }

  // ================= REGISTER =================
  Future<void> registerUser() async {
    if (namaController.text.isEmpty ||
        emailController.text.isEmpty ||
        passwordController.text.isEmpty ||
        noHpController.text.isEmpty ||
        selectedDesaId == null ||
        selectedDusunId == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text("Data wajib belum lengkap")),
      );
      return;
    }

    try {
      var url = Uri.parse("$baseUrl/register.php");

      var response = await http.post(url, body: {
        "nama": namaController.text,
        "email": emailController.text,
        "password": passwordController.text,
        "no_hp": noHpController.text,
        "nik": nikController.text,
        "desa_id": selectedDesaId,
        "dusun_id": selectedDusunId,
        "role": "ibu",
      });

      debugPrint("REGISTER RESPONSE: ${response.body}");

      var data = json.decode(response.body);

      if (data["success"] == true) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text("Registrasi berhasil, silakan login")),
        );

        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (_) => const LoginPage()),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(data["message"] ?? "Gagal daftar")),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("Error: $e")),
      );
    }
  }

  // ================= UI =================
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: const Color.fromARGB(255, 19, 133, 226),
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
        title: Text(
          "",
          style: GoogleFonts.poppins(
            color: Colors.white,
            fontWeight: FontWeight.w600,
          ),
        ),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(24),
            child: Column(
              children: [
                Text(
                  "M-Posyandu",
                  style: GoogleFonts.poppins(
                    fontSize: 26,
                    fontWeight: FontWeight.w700,
                  ),
                ),
                const SizedBox(height: 20),
                inputField("Nama Lengkap", namaController),
                inputField("Email", emailController),
                inputField("NIK", nikController),
                inputField("No HP", noHpController),
                inputField("Password", passwordController, isPassword: true),
                dropdownDesa(),
                dropdownDusun(),
                const SizedBox(height: 25),
                SizedBox(
                  width: double.infinity,
                  height: 50,
                  child: ElevatedButton(
                    onPressed: registerUser,
                    style: ElevatedButton.styleFrom(
                      backgroundColor:
                          const Color.fromARGB(255, 19, 133, 226),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(15),
                      ),
                    ),
                    child: Text(
                      "DAFTAR",
                      style: GoogleFonts.poppins(
                        color: Colors.white,
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // ================= DROPDOWN DESA =================
  Widget dropdownDesa() {
    return Padding(
      padding: const EdgeInsets.only(bottom: 15),
      child: DropdownButtonFormField<String>(
        value: selectedDesaId,
        isExpanded: true,
        decoration: InputDecoration(
          labelText: "Desa",
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(15),
          ),
        ),
        hint: const Text("Pilih Desa"),
        items: desaList.map<DropdownMenuItem<String>>((item) {
          return DropdownMenuItem<String>(
            value: item['id'].toString(),
            child: Text(item['nama_desa'] ?? '-'),
          );
        }).toList(),
        onChanged: (value) {
          setState(() {
            selectedDesaId = value;
            selectedDusunId = null;
            dusunList = [];
          });

          if (value != null) {
            fetchDusun(value);
          }
        },
      ),
    );
  }

  // ================= DROPDOWN DUSUN (FIXED) =================
  Widget dropdownDusun() {
    return Padding(
      padding: const EdgeInsets.only(bottom: 15),
      child: DropdownButtonFormField<String>(
        value: selectedDusunId,
        isExpanded: true,
        decoration: InputDecoration(
          labelText: "Dusun",
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(15),
          ),
        ),
        hint: const Text("Pilih Dusun"),

        // penting: disable kalau belum ada data
        onChanged: dusunList.isEmpty
            ? null
            : (value) {
                setState(() {
                  selectedDusunId = value;
                });
              },

        items: dusunList.map<DropdownMenuItem<String>>((item) {
          return DropdownMenuItem<String>(
            value: item['id'].toString(),
            child: Text(item['nama_dusun'] ?? '-'),
          );
        }).toList(),
      ),
    );
  }
}

// ================= INPUT FIELD =================
Widget inputField(String label, TextEditingController controller,
    {bool isPassword = false}) {
  return Padding(
    padding: const EdgeInsets.only(bottom: 15),
    child: TextField(
      controller: controller,
      obscureText: isPassword,
      decoration: InputDecoration(
        labelText: label,
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(15),
        ),
      ),
    ),
  );
}