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

class EditDusunPage extends StatefulWidget {
  final Map<String, dynamic> data;
  const EditDusunPage({super.key, required this.data});

  @override
  State<EditDusunPage> createState() => _EditDusunPageState();
}

class _EditDusunPageState extends State<EditDusunPage> {
  final _namaDusun = TextEditingController();
  bool _loading = false;
  final String url = "http://ta.myhost.id/E31230549/mposyandu_api/dusun/update_dusun.php";

  @override
  void initState() {
    super.initState();
    _namaDusun.text = widget.data["nama_dusun"] ?? "";
  }

  Future<void> _update() async {
    if (_namaDusun.text.trim().isEmpty) {
      _snack("Nama dusun wajib diisi");
      return;
    }
    setState(() => _loading = true);
    try {
      final res = await http.post(
        Uri.parse(url),
        body: {
          "id": widget.data["id"].toString(),
          "desa_id": widget.data["desa_id"]
              .toString(), // Tetap kirim ID dari data awal
          "nama_dusun": _namaDusun.text.trim(),
        },
      );
      final data = json.decode(res.body);
      if (data["success"] == true) {
        _snack("Berhasil update");
        Navigator.pop(context, true);
      }
    } catch (e) {
      _snack("Error koneksi");
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  void _snack(String msg) {
    ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(msg, style: GoogleFonts.poppins(fontSize: 12))));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xfff5f6fa),
      appBar: AppBar(
        leading: const BackButton(color: Colors.white),
        title: Text("",
            style: GoogleFonts.poppins(color: Colors.white, fontSize: 14)),
        backgroundColor: Colors.blue,
      ),
      body: Center(
        child: Container(
          width: 500,
          margin: const EdgeInsets.all(16),
          padding: const EdgeInsets.all(24),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(16),
            boxShadow: const [BoxShadow(color: Colors.black12, blurRadius: 12)],
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _label("Nama Dusun"),
              TextField(
                controller: _namaDusun,
                style: GoogleFonts.poppins(fontSize: 12),
                decoration: InputDecoration(
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10)),
                ),
              ),
              const SizedBox(height: 24),
              SizedBox(
                width: double.infinity,
                child: OutlinedButton(
                  onPressed: _loading ? null : _update,
                  style: OutlinedButton.styleFrom(
                    backgroundColor: Colors.white,
                    side: const BorderSide(color: Colors.orange, width: 1.5),
                    padding: const EdgeInsets.symmetric(vertical: 14),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10)),
                  ),
                  child: _loading
                      ? const SizedBox(
                          width: 20,
                          height: 20,
                          child: CircularProgressIndicator(
                              color: Colors.orange, strokeWidth: 2))
                      : Text("Simpan Perubahan",
                          style: GoogleFonts.poppins(
                              color: Colors.orange,
                              fontWeight: FontWeight.bold,
                              fontSize: 12)),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _label(String t) => Padding(
        padding: const EdgeInsets.only(bottom: 6),
        child: Text(t,
            style:
                GoogleFonts.poppins(fontWeight: FontWeight.w600, fontSize: 12)),
      );
}
