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

class EditImunisasiPage extends StatefulWidget {
  final Map data; // Menampung data yang dikirim dari halaman list

  const EditImunisasiPage({super.key, required this.data});

  @override
  State<EditImunisasiPage> createState() => _EditImunisasiPageState();
}

class _EditImunisasiPageState extends State<EditImunisasiPage> {
  final _formKey = GlobalKey<FormState>();

  late TextEditingController _idController;
  late TextEditingController _namaController;
  late TextEditingController _usiaMinController;
  late TextEditingController _usiaMaxController;
  late TextEditingController _ketController;

  bool isSubmitting = false;

  final String urlEdit =
      "http://ta.myhost.id/E31230549/mposyandu_api/imunisasi/edit_imunisasi.php";

  @override
  void initState() {
    super.initState();
    // Mengisi controller dengan data yang ada
    _idController = TextEditingController(text: widget.data['id'].toString());
    _namaController =
        TextEditingController(text: widget.data['nama_imunisasi']);
    _usiaMinController =
        TextEditingController(text: widget.data['usia_min'].toString());
    _usiaMaxController =
        TextEditingController(text: widget.data['usia_max'].toString());
    _ketController =
        TextEditingController(text: widget.data['keterangan'] ?? "");
  }

  Future _updateData() async {
    if (!_formKey.currentState!.validate()) return;

    setState(() => isSubmitting = true);

    try {
      final response = await http.post(
        Uri.parse(urlEdit),
        body: {
          "id": _idController.text, // Kirim ID sebagai kunci update
          "nama_imunisasi": _namaController.text,
          "usia_min": _usiaMinController.text,
          "usia_max": _usiaMaxController.text,
          "keterangan": _ketController.text,
        },
      );

      final data = jsonDecode(response.body);
      if (data['status'] == 'success') {
        if (!mounted) return;
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
              content: Text(data['message']), backgroundColor: Colors.blue),
        );
        Navigator.pop(context, true); // Kembali dan beri sinyal sukses
      } else {
        if (!mounted) return;
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(data['message']), backgroundColor: Colors.red),
        );
      }
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
            content: Text("Terjadi kesalahan: $e"),
            backgroundColor: Colors.red),
      );
    } finally {
      if (mounted) setState(() => isSubmitting = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F5),
      appBar: AppBar(
        backgroundColor: Colors.blue,
        elevation: 0,
        centerTitle: true,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
        title: Text(
          "",
          style: GoogleFonts.poppins(
              color: Colors.white, fontSize: 16, fontWeight: FontWeight.w600),
        ),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Center(
          child: Container(
            constraints: const BoxConstraints(maxWidth: 850),
            child: Card(
              elevation: 3,
              color: Colors.white,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10)),
              child: Padding(
                padding: const EdgeInsets.all(25),
                child: Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Center(
                        child: Text(
                          "Edit Jenis Imunisasi",
                          style: GoogleFonts.poppins(
                              fontSize: 18, fontWeight: FontWeight.bold),
                        ),
                      ),
                      const Divider(height: 40),
                      _buildLabel("Nama Imunisasi"),
                      _buildTextField(
                          _namaController, "Masukkan nama imunisasi"),
                      const SizedBox(height: 20),
                      Row(
                        children: [
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _buildLabel("Usia Min (Bulan)"),
                                _buildTextField(_usiaMinController, "0",
                                    isNumber: true),
                              ],
                            ),
                          ),
                          const SizedBox(width: 15),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _buildLabel("Usia Max (Bulan)"),
                                _buildTextField(_usiaMaxController, "12",
                                    isNumber: true),
                              ],
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 20),
                      _buildLabel("Keterangan"),
                      _buildTextField(_ketController, "Keterangan tambahan...",
                          maxLines: 3),
                      const SizedBox(height: 35),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          ElevatedButton(
                            onPressed: isSubmitting ? null : _updateData,
                            style: ElevatedButton.styleFrom(
                              backgroundColor:
                                  Colors.blue, // Warna orange untuk edit
                              padding: const EdgeInsets.symmetric(
                                  horizontal: 35, vertical: 12),
                              shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(8)),
                            ),
                            child: isSubmitting
                                ? const SizedBox(
                                    width: 16,
                                    height: 16,
                                    child: CircularProgressIndicator(
                                        color: Colors.white, strokeWidth: 2))
                                : Text(
                                    "Simpan Perubahan",
                                    style: GoogleFonts.poppins(
                                        fontSize: 12,
                                        color: Colors.white,
                                        fontWeight: FontWeight.bold),
                                  ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildLabel(String label) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Text(
        label,
        style: GoogleFonts.poppins(
            fontSize: 12, fontWeight: FontWeight.w600, color: Colors.black87),
      ),
    );
  }

  Widget _buildTextField(TextEditingController controller, String hint,
      {bool isNumber = false, int maxLines = 1}) {
    return TextFormField(
      controller: controller,
      keyboardType: isNumber ? TextInputType.number : TextInputType.text,
      maxLines: maxLines,
      style: const TextStyle(fontSize: 12),
      decoration: InputDecoration(
        hintText: hint,
        hintStyle: TextStyle(fontSize: 11, color: Colors.grey[400]),
        filled: true,
        fillColor: Colors.grey[50],
        contentPadding:
            const EdgeInsets.symmetric(vertical: 12, horizontal: 15),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: BorderSide(color: Colors.grey[300]!),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: const BorderSide(color: Colors.blue, width: 1.5),
        ),
        errorStyle: const TextStyle(fontSize: 10),
      ),
      validator: (value) =>
          value == null || value.isEmpty ? "Wajib diisi" : null,
    );
  }
}
