import 'dart:typed_data';
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:road24_mobile/data/response/manual_part/inspection/InspectionManualResponse.dart';

import 'details_new.dart';

class PlacesInMap extends StatefulWidget {
  final String? regionName;
  final LatLng defaultLocation;
  final List<Address>
      listOfPlaces; //to retrieve data from local, we need region Id;

  const PlacesInMap({
    Key? key,
    this.regionName,
    required this.listOfPlaces,
    required this.defaultLocation,
  }) : super(key: key);

  @override
  _PlacesInMapState createState() => _PlacesInMapState();
}

class _PlacesInMapState extends State<PlacesInMap>
    with AutomaticKeepAliveClientMixin {
  late BitmapDescriptor marker;
  ValueNotifier<Widget?> map = ValueNotifier(null);

  @override
  bool get wantKeepAlive => true;

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

  @override
  void dispose() {
    map.dispose();
    super.dispose();
  }

  Future<Uint8List> getBytesFromAsset(String path, int width) async {
    ByteData data = await rootBundle.load(path);
    Codec codec = await instantiateImageCodec(data.buffer.asUint8List(),
        targetWidth: width);
    FrameInfo fi = await codec.getNextFrame();
    return (await fi.image.toByteData(format: ImageByteFormat.png))!
        .buffer
        .asUint8List();
  }

  markerModify() async {
    final Uint8List markerIcon =
        await getBytesFromAsset('assets/png/location.png', 50);
    marker = BitmapDescriptor.fromBytes(markerIcon);
    List<Address> locations = widget.listOfPlaces;
    locations.removeWhere(
        (element) => element.geolocatoin.toString().split(',').length != 2);
    map.value = GoogleMap(
      initialCameraPosition: CameraPosition(
        target: widget.defaultLocation,
        zoom: 8,
      ),
      mapToolbarEnabled: true,
      markers: locations
          .map(
            (e) => Marker(
              markerId: MarkerId('${e.name}'),
              position: LatLng(double.tryParse(e.geolocatoin.split(',')[0])!,
                  double.tryParse(e.geolocatoin.split(',')[1])!),
              icon: marker,
              onTap: () {
                Navigator.push(
                    context,
                    CupertinoPageRoute(
                        builder: (context) => Details(
                              placeItem: e,
                            )));
              },
            ),
          )
          .toSet(),
      myLocationEnabled: true,
      myLocationButtonEnabled: true,
    );
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
        valueListenable: map,
        builder: (context, Widget? mapWidget, _) =>
            (mapWidget != null) ? mapWidget : const SizedBox());
  }
}
