import 'dart:async';
import 'dart:convert';

import 'package:siro_rider/constant/links.dart';
import 'package:siro_rider/controller/functions/crud.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:intaleq_maps/intaleq_maps.dart';

class TripMonitorController extends GetxController {
  bool isLoading = false;
  Map tripData = {};
  late String rideId;
  late String driverId;
  IntaleqMapController? mapController;
  List myListString = [];
  late Timer timer;
  late LatLng parentLocation;
  String carIcon = 'car';
  String motoIcon = 'moto';
  String ladyIcon = 'lady';
  double rotation = 0;
  double speed = 0;
  bool isStyleLoaded = false;

  Set<Marker> markers = {};

  getLocationParent() async {
    var res = await CRUD().get(
        link: AppLink.getLocationParents, payload: {"driver_id": driverId});
    if (res != 'failure') {
      tripData = jsonDecode(res);
      parentLocation = LatLng(
          double.parse(tripData['message'][0]['latitude'].toString()),
          double.parse(tripData['message'][0]['longitude'].toString()));
      rotation = double.parse(tripData['message'][0]['heading'].toString());
      speed = double.parse(tripData['message'][0]['speed'].toString());

      _updateMarker();
      update();
    }
  }

  void onMapCreated(IntaleqMapController controller) async {
    mapController = controller;
    update();
  }

  void onStyleLoaded() async {
    isStyleLoaded = true;
    mapController?.animateCamera(
      CameraUpdate.newLatLng(parentLocation),
    );
    _updateMarker();

    // Set up a timer or interval to trigger the marker update every 10 seconds.
    timer = Timer.periodic(const Duration(seconds: 10), (_) async {
      await getLocationParent();
      mapController?.animateCamera(CameraUpdate.newLatLng(parentLocation));
      update();
    });
  }

  void _updateMarker() {
    String iconPath = 'assets/images/car.png';
    if (tripData['message'] != null && tripData['message'].isNotEmpty) {
      final model = tripData['message'][0]['model'].toString();
      final gender = tripData['message'][0]['gender'].toString();
      if (model.contains('دراجة')) {
        iconPath = 'assets/images/moto1.png';
      } else if (gender == 'Female') {
        iconPath = 'assets/images/lady1.png';
      }
    }

    markers = {
      Marker(
        markerId: const MarkerId('driver'),
        position: parentLocation,
        icon: InlqBitmap.fromAsset(iconPath),
        rotation: rotation,
        anchor: const Offset(0.5, 0.5),
      ),
    };
    update();
  }

  Future<void> init({String? rideId, String? driverId}) async {
    this.driverId = driverId!;
    this.rideId = rideId!;
    await getLocationParent();
    update();
  }

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

  @override
  void onClose() {
    timer.cancel();
    mapController = null;
    super.onClose();
  }
}
