import 'dart:async';
import 'dart:ffi';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:image_picker/image_picker.dart';
import 'package:location/location.dart';
import 'package:mwf_app/service/assets.dart';
import 'package:mwf_app/service/color.dart';
import 'package:mwf_app/service/header.dart';
import 'package:mwf_app/service/loader.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/strings.dart';
import 'package:mwf_app/service/style.dart';
import 'package:mwf_app/model/map_location.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:mwf_app/service/navigator.dart';
import 'package:mwf_app/service/fontsize.dart';
import 'package:mwf_app/set1/customer_property_edit.dart';

class MapNavigationShow extends StatefulWidget {
  final isCustomer_prop;
  final latitude;
  final longitude;

  MapNavigationShow(
    this.isCustomer_prop,
    this.latitude,
    this.longitude,
  );

  @override
  _MapNavigationShowState createState() => _MapNavigationShowState(
        this.isCustomer_prop,
        this.latitude,
        this.longitude,
      );
}

class _MapNavigationShowState extends State<MapNavigationShow> {
  bool isLoading = true;
  bool isCustomer_prop = false;
  double latitude = 2.2;
  double longitude = 2.2;

  _MapNavigationShowState(
    this.isCustomer_prop,
    this.latitude,
    this.longitude,
  );

  List<Marker> myMarker = [];
  @override
  void initState() {
    super.initState();

    loadData();
    getLocation();
    wait();
    //isLoading = false;
    // MapLocation.data[0].latitude = latitude;
    //                       MapLocation.data[0].longtitude = longitude;
  }

  wait() async {
    await new Future.delayed(const Duration(milliseconds: 2000));
    setState(() {
      isLoading = false;
    });
  }

  getLocation() async {
    Location location = new Location();
    bool _serviceEnabled;
    PermissionStatus _permissionGranted;
    LocationData _locationData;

    _serviceEnabled = await location.serviceEnabled();
    if (!_serviceEnabled) {
      _serviceEnabled = await location.requestService();
      if (!_serviceEnabled) {
        return;
      }
    }

    _permissionGranted = await location.hasPermission();
    if (_permissionGranted == PermissionStatus.denied) {
      _permissionGranted = await location.requestPermission();
      if (_permissionGranted != PermissionStatus.granted) {
        return;
      }
    }

    _locationData = await location.getLocation();

    //  location.onLocationChanged.listen((LocationData currentLocation) {
    //    // Use current location
    //    print(currentLocation);
    //  });
  }

  loadData() async {
    final list = await MapLocation.getData(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api

    print(list);

    setState(() {
      final mapsList = MapLocation.fromJson(list);

      MapLocation.data.add(mapsList); // loop เก็บข้อมูล

      if (MapLocation.data.length > 0) {
        latitude = MapLocation.data[0].latitude;
        longitude = MapLocation.data[0].longtitude;
        myMarker.add(Marker(
          markerId: MarkerId(LatLng(latitude, longitude).toString()),
          position: LatLng(latitude, longitude),
        ));
      }
    });
  }

  @override
  Completer<GoogleMapController> _controller = Completer();

  Widget build(BuildContext context) {
    if (isLoading == true) {
      return AppLoader.loaderWaitPage();
    }
    // if (isLoading == true) {
    //   AppLoader.show();
    // }
    if (isLoading == false) {
      AppLoader.hide();
    }
    double _width = MediaQuery.of(context).size.width;
    double _height = MediaQuery.of(context).size.height;

    return Material(
      color: AppColors.bgColor,
      child: Stack(
        children: <Widget>[
          Header.header1(context),
          Header.mainMenu(context),
          Container(
            margin: EdgeInsets.only(
              top: mediaQuery(context, 'h', 950),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  (isCustomer_prop == true
                      ? AppStrings.Map_And_Navigation
                      : AppStrings.menu_map_user),
                  style: AppStyle.headTextStyle(context),
                ),
              ],
            ),
          ),
          Container(
            padding: EdgeInsets.only(
              left: 20,
              right: 20,
            ),
            width: _width,
            height: _height,
            margin: EdgeInsets.only(
              top: mediaQuery(context, 'h', 1100),
            ),
            child: Column(
              children: <Widget>[
                Container(
                  color: Colors.grey,
                  height: mediaQuery(context, "h", 890),
                  child: GoogleMap(
                    markers: Set.from(myMarker),
                    mapType: MapType.normal,
                    myLocationEnabled: true,
                    myLocationButtonEnabled: true,
                    tiltGesturesEnabled: true,
                    initialCameraPosition: CameraPosition(
                      target: LatLng(latitude, longitude), //bangkok
                      zoom: 15,
                    ),
                    onMapCreated: (GoogleMapController controller) {
                      _controller.complete(controller);
                    },
                    onTap: _handleTap,
                  ),
                ),
                if (isCustomer_prop == false) _buildSizeBox(context),
                _buildSizeBox(context),
                _buildSizeBox(context),
                isCustomer_prop != true
                    ? Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          MaterialButton(
                            onPressed: () {
                              openMap(latitude, longitude);
                            },
                            color: Colors.white,
                            textColor: Colors.white,
                            child: Image.asset(
                              AppAssets.google_map,
                              width: mediaQuery(context, "w", 100),
                              height: mediaQuery(context, "h", 100),
                            ),
                            padding: EdgeInsets.all(10),
                            shape: CircleBorder(),
                          ),
                          Text(
                            'นำทาง',
                            style: AppStyle.headTextStyle(context),
                          )
                        ],
                      )
                    : Text(''),
                //_buildSizeBox(context),
                //_buildSizeBox(context),
                //_buildSizeBox(context),
                if (isCustomer_prop == true)
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      _buildButton(
                          context, "บันทึก", AppColors.color, Colors.white),
                    ],
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  _buildSizeBox(context) {
    return SizedBox(
      height: mediaQuery(context, "h", 15),
    );
  }

  static Future<void> openMap(double latitude, double longitude) async {
    String googleUrl =
        'https://www.google.com/maps/search/?api=1&query=$latitude,$longitude';
    if (await canLaunch(googleUrl)) {
      await launch(googleUrl);
    } else {
      throw 'Could not open the map.';
    }
  }

  _handleTap(LatLng tappedPoint) {
    print(tappedPoint);
    if (myMarker.length < 0) {
      setState(() {
        myMarker = [];
      });
    } else {
      setState(() {
        myMarker = [];
        myMarker.add(Marker(
          markerId: MarkerId(tappedPoint.toString()),
          position: tappedPoint,
        ));
        latitude = tappedPoint.latitude;
        longitude = tappedPoint.longitude;
      });
    }
  }

  _buildButton(context, text, bgColor, fontColor) {
    double _width = MediaQuery.of(context).size.width;
    return ButtonTheme(
      minWidth: mediaQuery(context, "w", 1005),
      height: mediaQuery(context, "h", 120),
      child: FlatButton(
        shape: new RoundedRectangleBorder(
            borderRadius: new BorderRadius.circular(
              mediaQuery(context, "w", 50),
            ),
            side: BorderSide(color: AppColors.color)),
        color: bgColor,
        textColor: Colors.red,
        padding: EdgeInsets.all(
          mediaQuery(context, "w", 10),
        ),
        onPressed: () {
          print(text);
          if (text == "บันทึก") {
            _saveMap(context);
          }
        },
        child: Text(
          text,
          style: TextStyle(
            fontSize: mediaQuery(context, "h", 60),
            color: fontColor,
          ),
        ),
      ),
    );
  }

  _saveMap(context) async {
    var result = await MapLocation.updateData(
        context, latitude.toString(), longitude.toString());
    print(result);
    if (result == 'บันทึกสำเร็จ') {
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => CustomerPropertyEdit(),
        ),
      );
    }
  }
} //class
