import 'package:app/extensions/obtainProviderExtension.dart';
import 'package:app/state/mapState.dart';
import 'package:app/util/watchState.dart';
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:http/http.dart';
import 'package:http/retry.dart';
import 'package:latlong2/latlong.dart';

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

  @override
  State<MapView> createState() => _MapViewState();
}

class _MapViewState extends State<MapView> {
  @override
  Widget build(BuildContext context) {
    return FlutterMap(
      mapController: context.obtainState<MapState>().getMapController,
      options: MapOptions(
        onPositionChanged: (position, hasGesture) => {
          if (hasGesture) context.obtainState<MapState>().setLocationLive(false)
        },
        initialCenter: const LatLng(50.354, 7.5845),
        initialZoom: 16,
        interactionOptions: const InteractionOptions(
          flags: InteractiveFlag.all & ~InteractiveFlag.rotate
        )
      ),
      children: [
        TileLayer(
          urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
        ),
        TileLayer(
          urlTemplate: "https://bubatzkarte.de/tiles/radius/100/{z}/{x}/{y}.png",
          tileProvider: NetworkTileProvider(
              httpClient: RetryClient(
                  Client(),
                  when: (response) => response.statusCode >= 400 && response.statusCode != 404)
          ),
        ),
        WatchState<MapState>((context, state) => state.getActiveMarker != null ? MarkerLayer(
          markers: [
            Marker(
              point: state.getActiveMarker!,
              child: const Icon(
                Icons.location_on,
                color: Colors.red,
                size: 48,
              )
            )
          ],
        ) : const SizedBox.shrink()),
        WatchState<MapState>((context, state) => MarkerLayer(
          markers: [
            if (state.getActiveMarker != null) Marker(
              point: state.getActiveMarker!,
              child: const Icon(
                Icons.location_on,
                color: Colors.red,
                size: 48,
              )
            ),
            if (state.getCurrentLocation != null) Marker(
              point: state.getCurrentLocation!,
              child: const Stack(
                alignment: Alignment.center,
                children: [
                  Icon(
                    Icons.circle,
                    color: Colors.white,
                    size: 23,
                  ),
                  Icon(
                    Icons.circle,
                    color: Color.fromARGB(255, 0, 200, 0),
                    size: 16,
                  )
                ],
              )
            )
          ]
        ))
      ],
    );
  }
}
