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

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

  @override
  State<TambahDesaPage> createState() => _TambahDesaPageState();
}

class _TambahDesaPageState extends State<TambahDesaPage> {
  final _nama = TextEditingController();
  bool _loading = false;

  final String url = "http://ta.myhost.id/E31230549/mposyandu_api/desa/tambah_desa.php";

  bool _isValid() {
    if (_nama.text.isEmpty) {
      _snack("Nama desa wajib diisi");
      return false;
    }
    return true;
  }

  Future<void> _simpan() async {
    if (!_isValid()) return;

    setState(() => _loading = true);

    try {
      final res = await http.post(
        Uri.parse(url),
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
        body: {
          "nama": _nama.text,
        },
      ).timeout(const Duration(seconds: 15));

      if (!mounted) return;

      if (res.statusCode == 200 && res.body.isNotEmpty) {
        final data = json.decode(res.body);

        if (data["success"] == true) {
          _snack("Berhasil tambah desa");
          Navigator.pop(context, true);
        } else {
          _snack(data["message"] ?? "Gagal");
        }
      } else {
        _snack("Server error");
      }
    } catch (e) {
      debugPrint("POST ERROR: $e");
      if (mounted) _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: 16, fontWeight: FontWeight.w600),
        ),
        backgroundColor: Colors.blue,
      ),
      body: Center(
        child: SingleChildScrollView(
          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(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _label("Nama Desa"),
                _input(_nama),
                const SizedBox(height: 24),
                SizedBox(
                  width: double.infinity,
                  child: OutlinedButton(
                    onPressed: _loading ? null : _simpan,
                    style: OutlinedButton.styleFrom(
                      backgroundColor: Colors.white, // Background Putih
                      side: const BorderSide(
                          color: Colors.blue, width: 1.5), // Garis Tepi Biru
                      padding: const EdgeInsets.symmetric(vertical: 14),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10),
                      ),
                    ),
                    child: _loading
                        ? const SizedBox(
                            height: 20,
                            width: 20,
                            child: CircularProgressIndicator(
                                color: Colors.blue, strokeWidth: 2),
                          )
                        : Text(
                            "Simpan",
                            style: GoogleFonts.poppins(
                              color: Colors
                                  .blue, // Teks Biru agar senada dengan border
                              fontWeight: FontWeight.bold,
                              fontSize: 12,
                            ),
                          ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

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

  Widget _input(TextEditingController c) {
    return TextField(
      controller: c,
      style: GoogleFonts.poppins(fontSize: 12),
      decoration: InputDecoration(
        hintText: "Masukkan nama desa...",
        hintStyle: GoogleFonts.poppins(fontSize: 12, color: Colors.grey),
        contentPadding:
            const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: const BorderSide(color: Colors.grey),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: const BorderSide(color: Colors.blue, width: 1.5),
        ),
      ),
    );
  }
}
