import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import '../config.dart';
import 'laundry/map.dart';
import 'package:latlong2/latlong.dart';

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

  @override
  State<RequestPickupPage> createState() => _RequestPickupPageState();
}

class _RequestPickupPageState extends State<RequestPickupPage> {
  final _formKey = GlobalKey<FormState>();
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _addressController = TextEditingController();

  double? _latitude;
  double? _longitude;
  bool _isLoading = false;

  // --- Tailwind DESIGN TOKENS ---
  final Color primary = const Color(0xFF0058BE);
  final Color onPrimary = const Color(0xFFFFFFFF);
  final Color background = const Color(0xFFF7F9FB);
  final Color surfaceContainerLowest = const Color(0xFFFFFFFF);
  final Color onSurface = const Color(0xFF191C1E);
  final Color onSurfaceVariant = const Color(0xFF424754);
  final Color outlineVariant = const Color(0xFFC2C6D6);
  final Color successGreen = const Color(0xFF10B981);

  void _showSnackBar(String msg, Color bg) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Container(
        padding: const EdgeInsets.symmetric(vertical: 8),
        child: Row(
          children: [
            Icon(
              bg == const Color(0xFF10B981)
                  ? Icons.check_circle_outline
                  : Icons.error_outline_rounded,
              color: Colors.white,
              size: 28,
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    bg == const Color(0xFF10B981) ? "Berhasil" : "Peringatan",
                    style: GoogleFonts.inter(
                        fontWeight: FontWeight.w800,
                        fontSize: 14,
                        color: Colors.white),
                  ),
                  Text(
                    msg,
                    style: GoogleFonts.inter(
                        fontSize: 12,
                        color: Colors.white.withOpacity(0.9),
                        fontWeight: FontWeight.w500),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
      behavior: SnackBarBehavior.floating,
      backgroundColor: bg.withOpacity(0.95),
      elevation: 0,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(20),
        side: BorderSide(color: Colors.white.withOpacity(0.2), width: 1),
      ),
      duration: const Duration(seconds: 3),
    ));
  }

  Future<void> _submitPickup() async {
    if (!_formKey.currentState!.validate()) return;

    setState(() => _isLoading = true);

    try {
      final response = await http.post(
        Uri.parse("${AppConfig.baseUrl}/pickups"),
        headers: {
          'Authorization': 'Bearer ${widget.userData['access_token']}',
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        body: json.encode({
          'customer_name': _nameController.text.trim(),
          'phone': _phoneController.text.trim(),
          'address': _addressController.text.trim(),
          'latitude': _latitude,
          'longitude': _longitude,
        }),
      );

      if (response.statusCode == 201) {
        if (!mounted) return;
        _showSnackBar(
            "Jadwal jemput berhasil ditambahkan!", const Color(0xFF10B981));
        Navigator.pop(context, true); // Return true indicating success
      } else {
        if (!mounted) return;
        _showSnackBar("Gagal menambahkan jadwal jemput", Colors.redAccent);
      }
    } catch (e) {
      if (!mounted) return;
      _showSnackBar("Terjadi kesalahan koneksi", Colors.redAccent);
    } finally {
      if (mounted) setState(() => _isLoading = false);
    }
  }

  void _pickLocation() async {
    LatLng? initial = _latitude != null && _longitude != null
        ? LatLng(_latitude!, _longitude!)
        : null;

    final selectedLoc = await Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => MapPickerPage(initialLocation: initial)));

    if (selectedLoc != null && selectedLoc is LatLng) {
      setState(() {
        _latitude = selectedLoc.latitude;
        _longitude = selectedLoc.longitude;
        // Optionally update address field text if you implemented reverse geocoding,
        // but here we just store the coords.
      });
      _showSnackBar("Lokasi Peta berhasil dipilih!", const Color(0xFF10B981));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: background,
      appBar: AppBar(
        backgroundColor: surfaceContainerLowest,
        elevation: 0,
        iconTheme: IconThemeData(color: onSurface),
        title: Text("Jadwalkan Jemput",
            style: GoogleFonts.inter(
                color: onSurface, fontWeight: FontWeight.w700, fontSize: 18)),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(24),
          child: Form(
            key: _formKey,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text("Informasi Pelanggan",
                    style: GoogleFonts.inter(
                        fontSize: 16,
                        fontWeight: FontWeight.w700,
                        color: onSurface)),
                const SizedBox(height: 16),
                _buildTextField(
                    "Nama Pelanggan", Icons.person_rounded, _nameController),
                const SizedBox(height: 16),
                _buildTextField("Nomor WhatsApp", Icons.phone_android_rounded,
                    _phoneController,
                    isNumber: true),
                const SizedBox(height: 24),

                Text("Alamat Penjemputan",
                    style: GoogleFonts.inter(
                        fontSize: 16,
                        fontWeight: FontWeight.w700,
                        color: onSurface)),
                const SizedBox(height: 16),
                _buildTextField(
                    "Detail Alamat", Icons.home_rounded, _addressController,
                    maxLines: 3),
                const SizedBox(height: 12),

                // Map Picker Button
                SizedBox(
                  width: double.infinity,
                  child: OutlinedButton.icon(
                    onPressed: _pickLocation,
                    icon: Icon(Icons.pin_drop_rounded,
                        color: _latitude != null
                            ? successGreen
                            : primary),
                    label: Text(
                        _latitude != null
                            ? "Lokasi Maps Tersimpan"
                            : "Tandai Lokasi Penjemputan",
                        style: GoogleFonts.inter(
                            fontWeight: FontWeight.w600,
                            color: _latitude != null
                                ? successGreen
                                : primary)),
                    style: OutlinedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(vertical: 14),
                      side: BorderSide(
                          color: _latitude != null
                              ? successGreen
                              : outlineVariant,
                          width: 1),
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12)),
                    ),
                  ),
                ),

                const SizedBox(height: 40),

                SizedBox(
                  width: double.infinity,
                  height: 56,
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: primary,
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(16)),
                      elevation: 0,
                    ),
                    onPressed: _isLoading ? null : _submitPickup,
                    child: _isLoading
                        ? SizedBox(
                            width: 24,
                            height: 24,
                            child: CircularProgressIndicator(
                                color: onPrimary, strokeWidth: 2.5))
                        : Text("Kirim Tugas ke Driver",
                            style: GoogleFonts.inter(
                                fontSize: 16,
                                fontWeight: FontWeight.w800,
                                color: onPrimary)),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildTextField(
      String label, IconData icon, TextEditingController controller,
      {bool isNumber = false, int maxLines = 1}) {
    return TextFormField(
      controller: controller,
      keyboardType: isNumber ? TextInputType.phone : TextInputType.text,
      maxLines: maxLines,
      style: GoogleFonts.inter(
          fontSize: 14, fontWeight: FontWeight.w600, color: onSurface),
      decoration: InputDecoration(
        labelText: label,
        labelStyle: GoogleFonts.inter(color: onSurfaceVariant, fontSize: 13),
        prefixIcon:
            maxLines == 1 ? Icon(icon, color: onSurfaceVariant, size: 20) : null,
        filled: true,
        fillColor: surfaceContainerLowest,
        border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
            borderSide: BorderSide(color: outlineVariant)),
        enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
            borderSide: BorderSide(color: outlineVariant.withOpacity(0.5))),
        focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
            borderSide: BorderSide(color: primary)),
      ),
      validator: (val) =>
          (val == null || val.isEmpty) ? "Harap isi bidang ini" : null,
    );
  }
}
