import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:get/get.dart';
import 'package:latlong2/latlong.dart';
import 'package:rogapp/model/gps_data.dart';
import 'package:rogapp/pages/destination/destination_controller.dart';
import 'package:rogapp/pages/index/index_controller.dart';
import 'package:rogapp/utils/database_gps.dart';
import 'package:rogapp/widgets/base_layer_widget.dart';

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

  @override
  State<GpsPage> createState() => _GpsPageState();
}

class _GpsPageState extends State<GpsPage> {
  var gpsData = [].obs;
  MapController? mapController;
  StreamSubscription? subscription;
  final IndexController indexController = Get.find<IndexController>();
  final DestinationController destinationController =
      Get.find<DestinationController>();

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

  void loadGpsData() async {
    final team_name = indexController.currentUser[0]["user"]['team_name'];
    final event_code = indexController.currentUser[0]["user"]["event_code"];
    GpsDatabaseHelper db = GpsDatabaseHelper.instance;
    var data = await db.getGPSData(team_name, event_code);
    gpsData.value = data;

    //print("--- gps data ${data} ----");
  }

  Widget getMarkerShape(GpsData i) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        InkWell(
          onTap: () {},
          child: Container(
              height: 22,
              width: 22,
              decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.transparent,
                  border: Border.all(
                      color:
                          i.is_checkin == 0 ? Colors.blueAccent : Colors.green,
                      width: i.is_checkin == 0 ? 0.4 : 2,
                      style: BorderStyle.solid)),
              child: const Stack(
                alignment: Alignment.center,
                children: [
                  Icon(
                    Icons.circle,
                    size: 6.0,
                  ),
                ],
              )),
        ),
        Container(
            color: Colors.transparent,
            child: i.is_checkin == 1
                ? Text(
                    DateTime.fromMicrosecondsSinceEpoch(i.created_at)
                            .hour
                            .toString() +
                        ":" +
                        DateTime.fromMicrosecondsSinceEpoch(i.created_at)
                            .minute
                            .toString(),
                    // ":" +
                    // DateTime.fromMicrosecondsSinceEpoch(i.created_at)
                    //     .second
                    //     .toString(),
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.black,
                    ))
                : Container()),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("GPS way points"),
      ),
      body: Container(
          child: Obx(
        () => FlutterMap(
          mapController: mapController,
          options: MapOptions(
            maxZoom: 18.4,
            onMapReady: () {},
            //center: LatLng(37.15319600454702, 139.58765950528198),
            bounds: indexController.currentBound.isNotEmpty
                ? indexController.currentBound[0]
                : LatLngBounds.fromPoints([
                    LatLng(35.03999881162295, 136.40587119778962),
                    LatLng(36.642756778706904, 137.95226720406063)
                  ]),
            zoom: 1,
            interactiveFlags: InteractiveFlag.pinchZoom | InteractiveFlag.drag,

            onPositionChanged: (MapPosition pos, isvalue) {
              indexController.currentBound = [pos.bounds!];
            },
            onTap: (tapPos, cord) {}, // Hide popup when the map is tapped.
          ),
          children: [
            const BaseLayer(),
            MarkerLayer(
              markers: gpsData.map((i) {
                return Marker(
                  anchorPos: AnchorPos.exactly(Anchor(108.0, 18.0)),
                  height: 32.0,
                  width: 120.0,
                  point: LatLng(i.lat, i.lon),
                  builder: (ctx) {
                    return getMarkerShape(i);
                    // return Container(
                    //   width: 40,
                    //   height: 40,
                    //   color: Colors.orange,
                    // );
                  },
                );
              }).toList(),
            )
          ],
        ),
      )),
    );
  }
}
