import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import 'package:geolocator/geolocator.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';
import 'package:google_fonts/google_fonts.dart';
import 'dart:ui' as ui; // Solusi untuk mengatasi bentrok Path
import 'package:shared_preferences/shared_preferences.dart';

class MapPickerPage extends StatefulWidget {
  final LatLng? initialLocation;
  const MapPickerPage({super.key, this.initialLocation});

  @override
  State<MapPickerPage> createState() => _MapPickerPageState();
}

class _MapPickerPageState extends State<MapPickerPage> {
  // --- Tailwind DESIGN TOKENS ---
  final Color primary = const Color(0xFF0058BE);
  final Color onPrimary = const Color(0xFFFFFFFF);
  final Color primaryContainer = const Color(0xFF2170E4);
  final Color background = const Color(0xFFF7F9FB);
  final Color surface = const Color(0xFFF7F9FB);
  final Color surfaceContainerLowest = const Color(0xFFFFFFFF);
  final Color surfaceContainerLow = const Color(0xFFF0F4F8); 
  final Color onSurface = const Color(0xFF191C1E);
  final Color onSurfaceVariant = const Color(0xFF424754);
  final Color outlineVariant = const Color(0xFFC2C6D6);
  final Color outline = const Color(0xFF727785);

  LatLng _selectedLocation =
      const LatLng(-6.200000, 106.816666); // Default Jakarta
  final MapController _mapController = MapController();
  bool _isLoading = true;

  // Search variables
  final TextEditingController _searchController = TextEditingController();
  List<dynamic> _searchResults = [];
  Timer? _debounce;

  @override
  void initState() {
    super.initState();
    if (widget.initialLocation != null) {
      _selectedLocation = widget.initialLocation!;
    } else {
      _loadShopLocation();
    }
    _isLoading = false;
  }

  Future<void> _loadShopLocation() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final userStr = prefs.getString('userData');
      if (userStr != null) {
        final userData = json.decode(userStr);
        final shop = userData['shop'];
        if (shop != null) {
          final lat = shop['shop_latitude'] ?? shop['latitude'];
          final lng = shop['shop_longitude'] ?? shop['longitude'];
          if (lat != null && lng != null) {
            setState(() {
              _selectedLocation = LatLng(
                  double.parse(lat.toString()), double.parse(lng.toString()));
              _mapController.move(_selectedLocation, 15.0);
            });
          }
        }
      }
    } catch (e) {
      debugPrint("Gagal memuat lokasi toko: $e");
    }
  }

  @override
  void dispose() {
    _searchController.dispose();
    _debounce?.cancel();
    super.dispose();
  }

  Future<void> _determinePosition() async {
    bool serviceEnabled;
    LocationPermission permission;

    setState(() => _isLoading = true);

    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      setState(() => _isLoading = false);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('Layanan lokasi (GPS) tidak aktif. Silakan aktifkan terlebih dahulu.')));
      }
      return;
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        setState(() => _isLoading = false);
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('Izin lokasi ditolak oleh pengguna.')));
        }
        return;
      }
    }

    if (permission == LocationPermission.deniedForever) {
      setState(() => _isLoading = false);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: const Text('Izin lokasi ditolak permanen. Buka pengaturan untuk mengizinkan.'),
            action: SnackBarAction(
              label: 'PENGATURAN',
              textColor: Colors.white,
              onPressed: () {
                Geolocator.openAppSettings();
              },
            ),
          ),
        );
      }
      return;
    }

    try {
      Position position = await Geolocator.getCurrentPosition(
        locationSettings: const LocationSettings(
          accuracy: LocationAccuracy.high,
          timeLimit: Duration(seconds: 10),
        ),
      );
      if (mounted) {
        setState(() {
          _selectedLocation = LatLng(position.latitude, position.longitude);
          _isLoading = false;
        });
        _mapController.move(_selectedLocation, 16.0);
      }
    } catch (e) {
      if (mounted) {
        setState(() => _isLoading = false);
        ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('Gagal mendapatkan lokasi saat ini: $e')));
      }
    }
  }

  Future<void> _searchAddress(String query) async {
    if (query.isEmpty) {
      setState(() {
        _searchResults = [];
      });
      return;
    }

    try {
      final response = await http.get(
        Uri.parse(
            'https://nominatim.openstreetmap.org/search?q=$query&format=json&limit=5&addressdetails=1'),
        headers: {'User-Agent': 'laundry_mobile_app'},
      );

      if (response.statusCode == 200) {
        setState(() {
          _searchResults = json.decode(response.body);
        });
      }
      // ignore: empty_catches
    } catch (e) {}
  }

  void _onSearchChanged(String query) {
    if (_debounce?.isActive ?? false) _debounce?.cancel();
    _debounce = Timer(const Duration(milliseconds: 500), () {
      _searchAddress(query);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: background,
      appBar: AppBar(
        backgroundColor: Colors.white.withOpacity(0.95),
        elevation: 0,
        scrolledUnderElevation: 1,
        centerTitle: true,
        leading: IconButton(
          onPressed: () => Navigator.pop(context),
          icon:
              Icon(Icons.arrow_back_ios_new_rounded, color: onSurface, size: 20),
        ),
        title: Text("Pilih Lokasi Alamat",
            style: GoogleFonts.inter(
                color: onSurface, fontWeight: FontWeight.w700, fontSize: 16)),
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(1.0),
          child: Container(color: outlineVariant, height: 1.0),
        ),
      ),
      body: Stack(
        children: [
          FlutterMap(
            mapController: _mapController,
            options: MapOptions(
              initialCenter: _selectedLocation,
              initialZoom: 15,
              onPositionChanged: (position, hasGesture) {
                if (hasGesture) {
                  setState(() {
                    _selectedLocation = position.center;
                  });
                }
              },
            ),
            children: [
              TileLayer(
                urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
                userAgentPackageName: 'com.example.laundry_mobile',
              ),
            ],
          ),

          // Search Bar
          Positioned(
            top: 20,
            left: 20,
            right: 20,
            child: Column(
              children: [
                Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(16),
                    border: Border.all(color: outlineVariant, width: 2.0),
                    boxShadow: [
                      BoxShadow(
                        color: primary.withOpacity(0.06),
                        blurRadius: 20,
                        offset: const Offset(0, 8),
                      )
                    ],
                  ),
                  child: TextField(
                    controller: _searchController,
                    onChanged: _onSearchChanged,
                    style: GoogleFonts.inter(
                        fontWeight: FontWeight.w600,
                        color: onSurface,
                        fontSize: 14),
                    decoration: InputDecoration(
                      hintText: "Cari alamat atau nama tempat...",
                      hintStyle: GoogleFonts.inter(
                          color: onSurfaceVariant.withOpacity(0.6),
                          fontWeight: FontWeight.w500,
                          fontSize: 14),
                      prefixIcon: Icon(Icons.search_rounded,
                          color: primary, size: 22),
                      suffixIcon: _searchController.text.isNotEmpty
                          ? IconButton(
                              icon: Icon(Icons.cancel_rounded,
                                  size: 20, color: onSurfaceVariant),
                              onPressed: () {
                                _searchController.clear();
                                setState(() => _searchResults = []);
                              },
                            )
                          : null,
                      border: InputBorder.none,
                      contentPadding: const EdgeInsets.symmetric(vertical: 16),
                    ),
                  ),
                ),

                // Hasil Pencarian
                if (_searchResults.isNotEmpty)
                  Container(
                    margin: const EdgeInsets.only(top: 8),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(16),
                      border: Border.all(color: outlineVariant, width: 2.0),
                      boxShadow: [
                        BoxShadow(
                          color: primary.withOpacity(0.06),
                          blurRadius: 20,
                          offset: const Offset(0, 8),
                        )
                      ],
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(14),
                      child: ListView.separated(
                        shrinkWrap: true,
                        padding: EdgeInsets.zero,
                        itemCount: _searchResults.length,
                        separatorBuilder: (context, index) =>
                            Divider(height: 1, color: outlineVariant),
                        itemBuilder: (context, index) {
                          final item = _searchResults[index];
                          return ListTile(
                            contentPadding: const EdgeInsets.symmetric(
                                horizontal: 16, vertical: 4),
                            leading: Container(
                              padding: const EdgeInsets.all(8),
                              decoration: BoxDecoration(
                                  color: background,
                                  borderRadius: BorderRadius.circular(10),
                                  border: Border.all(color: outlineVariant)),
                              child: Icon(Icons.location_on_rounded,
                                  size: 20, color: primary),
                            ),
                            title: Text(
                              item['display_name'],
                              style: GoogleFonts.inter(
                                  fontSize: 13,
                                  fontWeight: FontWeight.w500,
                                  color: onSurface),
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                            ),
                            onTap: () {
                              final lat = double.parse(item['lat']);
                              final lon = double.parse(item['lon']);
                              final newPos = LatLng(lat, lon);
                              setState(() {
                                _selectedLocation = newPos;
                                _searchResults = [];
                                _searchController.text = item['display_name'];
                              });
                              _mapController.move(newPos, 16.0);
                              FocusScope.of(context).unfocus();
                            },
                          );
                        },
                      ),
                    ),
                  ),
              ],
            ),
          ),

          // Center Marker
          Center(
            child: Padding(
              padding: const EdgeInsets.only(bottom: 35),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                        color: primary,
                        shape: BoxShape.circle,
                        boxShadow: [
                          BoxShadow(
                              color: primary.withOpacity(0.4),
                              blurRadius: 12,
                              offset: const Offset(0, 6))
                        ],
                        border: Border.all(color: Colors.white, width: 3)),
                    child: const Icon(Icons.location_on_rounded,
                        color: Colors.white, size: 28),
                  ),
                  // Segitiga kecil dibawah marker
                  ClipPath(
                    clipper: _TriangleClipper(),
                    child: Container(
                      width: 14,
                      height: 10,
                      color: primary,
                    ),
                  )
                ],
              ),
            ),
          ),

          // Loading Overlay
          if (_isLoading)
            Container(
              color: Colors.white.withOpacity(0.8),
              child:
                  Center(child: CircularProgressIndicator(color: primary)),
            ),

          // UI Buttons Bottom
          Positioned(
            bottom: 24,
            left: 20,
            right: 20,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                // Tombol My Location
                InkWell(
                  onTap: _determinePosition,
                  borderRadius: BorderRadius.circular(16),
                  child: Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(16),
                      border: Border.all(color: outlineVariant, width: 2.0),
                      boxShadow: [
                        BoxShadow(
                          color: primary.withOpacity(0.06),
                          blurRadius: 15,
                          offset: const Offset(0, 5),
                        )
                      ],
                    ),
                    child: Icon(Icons.my_location_rounded,
                        color: primary, size: 24),
                  ),
                ),
                const SizedBox(height: 16),

                // Panel Konfirmasi
                Container(
                  padding: const EdgeInsets.all(20),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(24),
                    border: Border.all(color: outlineVariant, width: 2.0),
                    boxShadow: [
                      BoxShadow(
                        color: primary.withOpacity(0.08),
                        blurRadius: 24,
                        offset: const Offset(0, 10),
                      )
                    ],
                  ),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        "Geser peta untuk menentukan titik alamat",
                        textAlign: TextAlign.center,
                        style: GoogleFonts.inter(
                          color: onSurfaceVariant,
                          fontSize: 13,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      const SizedBox(height: 16),
                      SizedBox(
                        width: double.infinity,
                        height: 54,
                        child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: primary,
                            foregroundColor: Colors.white,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(16),
                            ),
                            elevation: 0,
                          ),
                          onPressed: () {
                            Navigator.pop(context, _selectedLocation);
                          },
                          child: Text(
                            "KONFIRMASI LOKASI",
                            style: GoogleFonts.inter(
                              color: Colors.white,
                              fontWeight: FontWeight.w700,
                              fontSize: 15,
                              letterSpacing: 0.5,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

// Menggunakan ui.Path agar tidak tertukar dengan Path milik latlong2
class _TriangleClipper extends CustomClipper<ui.Path> {
  @override
  ui.Path getClip(Size size) {
    final path = ui.Path();
    path.lineTo(size.width, 0.0);
    path.lineTo(size.width / 2, size.height);
    path.close();
    return path;
  }

  @override
  bool shouldReclip(_TriangleClipper oldClipper) => false;
}
