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

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

  @override
  State<TambahImunisasiPage> createState() => _TambahImunisasiPageState();
}

class _TambahImunisasiPageState extends State<TambahImunisasiPage> {
  final _formKey = GlobalKey<FormState>();

  final TextEditingController _namaController = TextEditingController();
  final TextEditingController _usiaMinController = TextEditingController();
  final TextEditingController _usiaMaxController = TextEditingController();
  final TextEditingController _ketController = TextEditingController();

  bool isSubmitting = false;

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

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

    setState(() => isSubmitting = true);

    try {
      final response = await http.post(
        Uri.parse(urlTambah),
        body: {
          "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(
          const SnackBar(content: Text("Data berhasil disimpan!")),
        );
        Navigator.pop(context);
      }
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("Terjadi kesalahan: $e")),
      );
    } 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: [
                      // --- JUDUL ---
                      Center(
                        child: Text(
                          "Tambah 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,
                          "Contoh: Diberikan pada bayi baru lahir",
                          maxLines: 3),

                      const SizedBox(height: 35),

                      // --- TOMBOL SIMPAN (OUTLINED STADIUM - TANPA IKON) ---
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          SizedBox(
                            width: 150, // Menentukan lebar agar proporsional
                            child: OutlinedButton(
                              onPressed: isSubmitting ? null : _simpanData,
                              style: OutlinedButton.styleFrom(
                                side: const BorderSide(color: Colors.blue, width: 1.5),
                                shape: const StadiumBorder(),
                                padding: const EdgeInsets.symmetric(vertical: 12),
                              ),
                              child: isSubmitting
                                  ? const SizedBox(
                                      width: 18,
                                      height: 18,
                                      child: CircularProgressIndicator(
                                          color: Colors.blue, strokeWidth: 2))
                                  : Text(
                                      "Simpan",
                                      style: GoogleFonts.poppins(
                                          fontSize: 12,
                                          color: Colors.blue,
                                          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,
    );
  }
}