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:gifunavi/model/gps_data.dart';
import 'package:gifunavi/pages/destination/destination_controller.dart';
import 'package:gifunavi/pages/index/index_controller.dart';
import 'package:gifunavi/utils/database_gps.dart';
import 'package:gifunavi/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();
  }

  // 要検討：GPSデータの読み込みに失敗した場合のエラーハンドリングが不十分です。適切なエラーメッセージを表示するなどの処理を追加してください。
  //
  void loadGpsData() async {
    final teamName = indexController.currentUser[0]["user"]['team_name'];
    final eventCode = indexController.currentUser[0]["user"]["event_code"];
    GpsDatabaseHelper db = GpsDatabaseHelper.instance;
    var data = await db.getGPSData(teamName, eventCode);
    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("movement_history".tr),
      ),
      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([
                    const LatLng(35.03999881162295, 136.40587119778962),
                    const LatLng(36.642756778706904, 137.95226720406063)
                  ]),
            zoom: 1,
            interactiveFlags: InteractiveFlag.pinchZoom | InteractiveFlag.drag,
            onPositionChanged: (MapPosition pos, bool hasGesture) {
              if (hasGesture) {
                indexController.currentBound = [pos.bounds!];
              }
            },
            onTap: (tapPos, cord) {}, // Hide popup when the map is tapped.
          ),
          children: [
            const BaseLayer(),
            MarkerLayer(
              markers: gpsData.map((i) {
                return Marker(
                    width: 30.0, // Fixed width
                    height: 30.0, // Fixed height
                    point: LatLng(i.lat, i.lon),
                    child: getMarkerShape(i),
                    alignment: Alignment.center);
              }).toList(),
            ),
            // MarkerLayer(
            //   markers: gpsData.map((i) {
            //     return Marker(
            //         alignment: Alignment.center,
            //         height: 32.0,
            //         width: 120.0,
            //         point: LatLng(i.lat, i.lon),
            //         child: getMarkerShape(i));
            //   }).toList(),
            // )
          ],
        ),
      )),
    );
  }
}
