import 'dart:async';

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

import '../../consts/consts.dart';
import '../../packages/ambito_theme/ambito_theme.dart';

class MapWidget extends StatefulWidget {
  const MapWidget({
    super.key,
    required this.initialPosition, // Make initial position required
    this.markers = const {}, // Provide default empty sets
    this.polygons = const {},
    this.polylines = const {},
  });

  final LatLng initialPosition; // Use LatLng directly
  final Set<Marker> markers;
  final Set<Polygon> polygons;
  final Set<Polyline> polylines;

  @override
  State<MapWidget> createState() => _MapWidgetState(); // Use shorter syntax
}

class _MapWidgetState extends State<MapWidget> {
  final Completer<GoogleMapController> _controller = Completer();
  bool _drawPolygon = false;
  int _counter = 0;

  late CameraPosition _initialCameraPosition; // Use late for initialization

  @override
  void initState() {
    super.initState();
    _initialCameraPosition = CameraPosition(
      target: widget.initialPosition,
      zoom: 14,
    );
  }

  @override
  void didUpdateWidget(covariant MapWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.initialPosition != widget.initialPosition) {
      _initialCameraPosition = CameraPosition(
        target: widget.initialPosition,
        zoom: 14,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final AmbitoTheme theme = getTheme(context);
    return ClipRRect(
      borderRadius: BorderRadius.circular(10.0),
      child: SizedBox(
        width: double.infinity,
        child: Column(
          children: [
            Expanded(
              child: GoogleMap(
                onTap: _handleMapTap, // Extract onTap logic
                mapToolbarEnabled: true,
                mapType: MapType.hybrid,
                markers: widget.markers,
                polygons: widget.polygons,
                polylines: widget.polylines,
                initialCameraPosition: _initialCameraPosition,
                onMapCreated: (GoogleMapController controller) {
                  _controller.complete(controller);
                },
              ),
            ),
            Row(
              children: [
                const Spacer(),
                IconButton(
                  onPressed: () => setState(
                      () => _drawPolygon = !_drawPolygon), // Shorter syntax
                  icon: Icon(
                    Icons.polyline_outlined,
                    color: _drawPolygon
                        ? theme.currentColorScheme.primary
                        : theme.currentColorScheme.outline,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  void _handleMapTap(LatLng position) {
    final AmbitoTheme theme = getTheme(context);
    if (_drawPolygon) {
      setState(() {
        final markerId = MarkerId('polygon_$_counter');
        widget.markers.add(
          Marker(
            onTap: () => _onTapMarker(markerId.value), // Use closure for onTap
            markerId: markerId,
            position: position,
          ),
        );

        if (_counter > 0) {
          final previousMarkerId = MarkerId('polygon_${_counter - 1}');
          final previousMarker = widget.markers.firstWhere(
            (el) => el.markerId == previousMarkerId,
            orElse: () => Marker(
                markerId: const MarkerId('invalid'),
                position: const LatLng(
                    0, 0)), // Provide a default in case it is not found
          );

          if (previousMarker.markerId.value != 'invalid') {
            widget.polylines.add(
              Polyline(
                polylineId: PolylineId('polyline_$_counter'),
                color: theme.currentColorScheme.primary,
                width: 2,
                points: [previousMarker.position, position],
              ),
            );
          } else {
            logger.w('Previous marker not found');
          }
        }
        _counter++;
      });
    }
  }

  void _onTapMarker(String markerId) {
    logger.d(markerId);
    if (markerId == 'polygon_0') {
      logger.d('first pressed');
    }
  }
}
