import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:go_router/go_router.dart';
import 'package:latlong2/latlong.dart';
import 'package:niogu_app/core/components/top_back_bar_app.dart';
import 'package:niogu_app/core/constants/app_color.dart';
import 'package:niogu_app/core/constants/app_font_size.dart';
import 'package:niogu_app/core/widgets/triangle_painter.dart';
import 'package:niogu_app/features/outlets/domain/entities/outlet.dart';
import 'package:niogu_app/features/outlets/presentation/providers/outlet_provider.dart';
import 'package:sizer/sizer.dart';

class MapOutletAddressScreen extends ConsumerStatefulWidget {
  const MapOutletAddressScreen({super.key});

  @override
  ConsumerState<MapOutletAddressScreen> createState() =>
      _MapOutletAddressScreenState();
}

class _MapOutletAddressScreenState
    extends ConsumerState<MapOutletAddressScreen> {
  final MapController _mapController = MapController();

  final TextEditingController _addressController = TextEditingController();

  LatLng _currentLocation = const LatLng(-6.2000, 106.8166);

  bool _isLoading = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    final mapOutletAddress = ref.read(mapOutletAddressProvider);

    if (mapOutletAddress != null) {
      _addressController.text = mapOutletAddress.fullAddress;

      _currentLocation = mapOutletAddress.currentLocation;
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _mapController.dispose();
    _addressController.dispose();
    super.dispose();
  }

  Future<void> _getCurrentPosition() async {
    setState(() => _isLoading = true);

    final bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) return;

    LocationPermission permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) return;
    }

    Position position = await Geolocator.getCurrentPosition();
    setState(() {
      _currentLocation = LatLng(position.latitude, position.longitude);
      _mapController.move(_currentLocation, 15.0);
      _isLoading = false;
    });

    try {
      final List<Placemark> placemarks = await placemarkFromCoordinates(
        position.latitude,
        position.longitude,
      );
      if (placemarks.isNotEmpty) {
        final Placemark place = placemarks[0];
        _addressController.text =
            "${place.street}, ${place.subLocality}, ${place.locality}, ${place.subAdministrativeArea}, ${place.administrativeArea}, ${place.postalCode}";
      }
    } catch (e) {
      debugPrint(e.toString());
      setState(() => _isLoading = true);
    }
  }

  void _selectedCurrentLocation() {
    final fullAddress = _addressController.text;

    ref.read(mapOutletAddressProvider.notifier).state = OutletAddressSelected(
      fullAddress: fullAddress,
      currentLocation: _currentLocation,
    );

    context.pop();
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            extendBodyBehindAppBar: true,
            appBar: TopBackBarApp(
              title: "Alamat Outlet",
              onTap: () => context.pop(),
            ),
            body: Column(
              children: [
                Expanded(
                  child: Stack(
                    children: [
                      FlutterMap(
                        mapController: _mapController,
                        options: MapOptions(
                          initialCenter: _currentLocation,
                          initialZoom: 16.0,
                          minZoom: 3.0,
                          maxZoom: 18.0,
                        ),
                        children: [
                          TileLayer(
                            urlTemplate:
                                'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png',
                            subdomains: const ['a', 'b', 'c', 'd'],
                            userAgentPackageName: 'com.example.niogu_app',
                          ),
                          MarkerLayer(
                            markers: [
                              Marker(
                                point: _currentLocation,
                                width: 70.w,
                                height: 25.h,
                                alignment: Alignment.topCenter,
                                child: _addressController.text.isEmpty
                                    ? const SizedBox()
                                    : Column(
                                        mainAxisSize: MainAxisSize.min,
                                        children: [
                                          Container(
                                            padding: EdgeInsets.symmetric(
                                              horizontal: 3.w,
                                              vertical: 1.2.h,
                                            ),
                                            constraints: BoxConstraints(
                                              maxWidth: 65.w,
                                            ),
                                            decoration: BoxDecoration(
                                              color: Colors.white,
                                              borderRadius:
                                                  BorderRadius.circular(2.w),
                                              boxShadow: [
                                                BoxShadow(
                                                  color: Colors.black
                                                      .withOpacity(0.1),
                                                  blurRadius: 8,
                                                  offset: const Offset(0, 4),
                                                ),
                                              ],
                                              border: Border.all(
                                                color: Colors.grey.shade200,
                                              ),
                                            ),
                                            child: Column(
                                              mainAxisSize: MainAxisSize.min,
                                              children: [
                                                Row(
                                                  mainAxisAlignment:
                                                      MainAxisAlignment
                                                          .spaceBetween,
                                                  children: [
                                                    SizedBox(width: 5.w),
                                                    Text(
                                                      "Lokasi Outlet",
                                                      textAlign:
                                                          TextAlign.center,
                                                      style: TextStyle(
                                                        fontSize: AppFontSize
                                                            .small
                                                            .sp,
                                                        fontWeight:
                                                            FontWeight.bold,
                                                        color: AppColor
                                                            .primaryColor,
                                                      ),
                                                    ),

                                                    InkWell(
                                                      onTap: () {
                                                        setState(() {
                                                          _addressController
                                                              .clear();
                                                        });
                                                      },
                                                      child: Icon(
                                                        Icons.close,
                                                        color: Colors.grey,
                                                        size: 5.w,
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                                SizedBox(height: 0.5.h),
                                                Text(
                                                  _addressController.text,
                                                  textAlign: TextAlign.center,
                                                  style: TextStyle(
                                                    fontSize:
                                                        (AppFontSize.small -
                                                                1.25)
                                                            .sp,
                                                    color: Colors.grey[700],
                                                    fontWeight: FontWeight.w500,
                                                    height: 1.4,
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                          CustomPaint(
                                            size: Size(5.w, 2.5.w),
                                            painter: TrianglePainter(
                                              Colors.white,
                                            ),
                                          ),
                                          SizedBox(height: 0.5.h),
                                          Icon(
                                            Icons.location_on,
                                            color: Colors.red,
                                            size: 10.w,
                                          ),
                                        ],
                                      ),
                              ),
                            ],
                          ),
                        ],
                      ),

                      Positioned(
                        bottom: 3.h,
                        left: 5.w,
                        right: 5.w,
                        child: OutlinedButton.icon(
                          onPressed: _addressController.text.isNotEmpty
                              ? _selectedCurrentLocation
                              : _getCurrentPosition,
                          icon: _addressController.text.isNotEmpty
                              ? null
                              : Icon(
                                  Icons.my_location,
                                  size: 5.w,
                                  color: AppColor.primaryColor,
                                ),
                          label: Text(
                            _addressController.text.isNotEmpty
                                ? "Pilih Lokasi Ini"
                                : "Gunakan Lokasi Saat Ini",
                            style: TextStyle(
                              fontSize: (AppFontSize.medium).sp,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          style: OutlinedButton.styleFrom(
                            minimumSize: Size(double.infinity, 5.h),
                            foregroundColor: AppColor.primaryColor,
                            side: BorderSide(color: AppColor.primaryColor),
                          ),
                        ),
                      ),

                      if (_isLoading)
                        Container(
                          color: Colors.white.withOpacity(0.3),
                          child: Center(
                            child: CircularProgressIndicator(
                              color: Colors.grey.shade700,
                            ),
                          ),
                        ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
