import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:prosappco/src/authentication/authentication_repository.dart';
import 'package:prosappco/src/components/pop_appbar.dart';
import 'package:prosappco/src/components/primary_btn.dart';

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

  @override
  State<ProfessionalDireccionScreen> createState() =>
      _ProfessionalDireccionScreenState();
}

class _ProfessionalDireccionScreenState
    extends State<ProfessionalDireccionScreen> {
  final TextEditingController _locationController = TextEditingController();
  final String _locationPosition = '';
  final uid = AuthenticationRepository.instance.getCurrentUserUid();

  late GoogleMapController googleMapController;

  static const CameraPosition initialCameraPosition = CameraPosition(
    target: LatLng(7.8939100, -72.5078200),
    zoom: 14.4746,
  );

  Set<Marker> markers = {};

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

    serviceEnabled = await Geolocator.isLocationServiceEnabled();

    if (!serviceEnabled) {
      return Future.error('Location services are disabled');
    }

    permission = await Geolocator.checkPermission();

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

      if (permission == LocationPermission.denied) {
        return Future.error('Location permission denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      return Future.error('Location permissions are permanently denied');
    }

    Position position = await Geolocator.getCurrentPosition();

    return position;
  }

  @override
  void initState() {
    super.initState();
  }

  late String lat;
  late String long;
  var coordinates;

  Future<String> getLocationName(double latitude, double longitude) async {
    String address;
    List<Placemark> placemarks =
        await placemarkFromCoordinates(latitude, longitude);
    Placemark place = placemarks[0];

    if (place.thoroughfare != '' || place.subThoroughfare != '') {
      address =
          "${place.thoroughfare} ${place.subThoroughfare} ${place.subLocality}, ${place.locality}, ${place.administrativeArea}";
    } else {
      address = '';
    }
    return address;
  }

  Future<void> updateAddress(
      String addressName, double latitude, double longitude) async {
    try {
      await FirebaseFirestore.instance.collection('users').doc(uid).update({
        'address': addressName,
        'latitude': latitude,
        'longitude': longitude,
      });
    } catch (e) {
      try {
        await FirebaseFirestore.instance.collection('users').doc(uid).set({
          'address': addressName,
          'latitude': latitude,
          'longitude': longitude,
        });
      } catch (e) {
        print('Error al agregar la ciudad: $e');
      }

      print('Error al actualizar la ciudad: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: PopAppbar(
            onPressed: () {
              Navigator.pop(context);
            },
            label: 'Ubicación'),
        backgroundColor: const Color(0xFFD6F4FF),
        body: Stack(
          children: [
            GoogleMap(
              mapType: MapType.normal,
              initialCameraPosition: initialCameraPosition,
              markers: markers,
              zoomControlsEnabled: false,
              onMapCreated: (GoogleMapController controller) {
                googleMapController = controller;
              },
              onCameraIdle: () {
                if (coordinates != null) {
                  getLocationName(coordinates.latitude, coordinates.longitude)
                      .then((locationName) {
                    setState(() {
                      _locationController.text = locationName;
                    });
                  });
                }
              },
              onCameraMove: (position) {
                setState(() {
                  coordinates = position.target;
                });
              },
              gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{
                Factory<OneSequenceGestureRecognizer>(
                  () => EagerGestureRecognizer(),
                ),
              },
            ),
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.5),
                    spreadRadius: 1,
                    blurRadius: 5,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: Padding(
                padding: const EdgeInsets.only(
                    left: 35, right: 35, bottom: 15, top: 5),
                child: TextFormField(
                  controller: _locationController,
                  decoration: const InputDecoration(
                    prefixIcon: Icon(Icons.near_me),
                    hintText: 'Dirección',
                  ),
                ),
              ),
            ),
            const Positioned(
              bottom: 10,
              right: 0,
              left: 0,
              top: 0,
              child: Icon(
                Icons.location_on,
                size: 40,
                color: Colors.red,
              ),
            ),
            Positioned(
              bottom: 130,
              right: 20,
              child: FloatingActionButton(
                onPressed: () async {
                  try {
                    Position position = await _determinePosition();

                    googleMapController.animateCamera(
                      CameraUpdate.newCameraPosition(
                        CameraPosition(
                            target: LatLng(
                              position.latitude,
                              position.longitude,
                            ),
                            zoom: 17),
                      ),
                    );
                    setState(() {});
                  } catch (e) {
                    Get.snackbar(
                      'ubicación desactivada',
                      'Por favor activa la ubicacion de tu telefono.',
                      snackPosition: SnackPosition.TOP,
                    );
                  }

                  // markers.clear();

                  // markers.add(Marker(
                  //     markerId: const MarkerId('currentLocation'),
                  //     position:
                  //         LatLng(position.latitude, position.longitude)));
                },
                elevation: 0,
                child: const Icon(
                  Icons.gps_fixed,
                  size: 30,
                ),
              ),
            ),
            Positioned(
              bottom: 30,
              left: 0,
              right: 0,
              child: SizedBox(
                width: MediaQuery.of(context).size.width,
                child: Align(
                  alignment: Alignment.center,
                  child: PrimaryButtom(
                      onPressed: () {
                        updateAddress(
                          _locationController.text,
                          coordinates.latitude,
                          coordinates.longitude,
                        );
                        Navigator.pop(context, _locationController.text);
                      },
                      label: 'Guardar'),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
