import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:fluttericon/entypo_icons.dart';
import 'package:latlong/latlong.dart';
import 'package:location/location.dart';
import 'package:peasmartcare/blocs/electricity_location_current/electricity_location_current_bloc.dart';
import 'package:peasmartcare/constraints/app_data.dart';
import 'package:peasmartcare/models/electricity_location_lat_long_model.dart';
import 'package:peasmartcare/pages/auth/logout.dart';
import 'package:peasmartcare/pages/electricity_location/electricity_location_map_current_location.dart';
import 'package:peasmartcare/pages/electricity_location/electricity_location_map_loading_location.dart';
import 'package:peasmartcare/pages/electricity_location/electricity_location_map_save_location.dart';

class ElectricityLocationMap extends StatefulWidget {
  @override
  _ElectricityLocationMapState createState() => _ElectricityLocationMapState();
}

class _ElectricityLocationMapState extends State<ElectricityLocationMap> {
  LocationData _currentLocation;
  MapController _mapController;
  LatLng currentLatLng;
  LatLng _myCurrentLatLng;
  LatLng _currentMarkerLatLng;

  // bool _permission = false;

  String _serviceError = '';

  final Location _locationService = Location();

  @override
  void initState() {
    super.initState();
    _mapController = MapController();

    initLocationService();
    context.read<ElectricityLocationCurrentBloc>().add(ElectricityLocationCurrentGetCurrent());
  }

  @override
  Widget build(BuildContext context) {
    Size deviceSize = MediaQuery.of(context).size;
    LatLng _currentLatLng = currentLatLng;

    if (_currentLatLng == null) {
      _currentLatLng = LatLng(0, 0);
    }

    var markers = <Marker>[
      Marker(
        width: 50,
        height: 50,
        point: _myCurrentLatLng,
        builder: (ctx) => Container(
          child: Icon(
            Entypo.target,
            color: Color(AppData.blueColor),
            size: 25,
          ),
        ),
      ),
      Marker(
        width: 50,
        height: 50,
        point: _currentMarkerLatLng,
        builder: (ctx) => Container(
          child: Icon(
            Icons.location_on,
            color: Color(AppData.redColor),
            size: 30,
          ),
        ),
      ),
    ];

    return BlocListener<ElectricityLocationCurrentBloc, ElectricityLocationCurrentState>(
      listener: (context, state) {
        if (state is ElectricityLocationCurrentLoaded) {
          ElectricityLocationLatLongModel latLong = state.result;

          if (latLong != null) {
            _mapController.move(
              LatLng(
                latLong.latitude,
                latLong.longitude,
              ),
              _mapController.zoom,
            );

            setState(() {
              currentLatLng = LatLng(latLong.latitude, latLong.longitude);
              _currentMarkerLatLng = currentLatLng;
            });
          } else {
            _currentMarkerLatLng = LatLng(0, 0);
          }
        } else if (state is ElectricityLocationCurrentErrorUnauthorized) {
          Navigator.of(context).popUntil((route) => route.isFirst);
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (context) => LogoutPage()),
          );
        }
      },
      child: Container(
        height: deviceSize.height - 230,
        margin: EdgeInsets.zero,
        padding: EdgeInsets.zero,
        child: FlutterMap(
          mapController: _mapController,
          options: MapOptions(
            center: LatLng(_currentLatLng.latitude, _currentLatLng.longitude),
            zoom: 15,
            onTap: _handleTap,
            plugins: [
              CurrentLocationPlugin(),
              SaveLocationPlugin(),
              LoadingLocationPlugin(),
            ],
          ),
          layers: [
            TileLayerOptions(
              urlTemplate: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
              subdomains: ['a', 'b', 'c'],
              tileProvider: NonCachingNetworkTileProvider(),
            ),
            CurrentLocationPluginOption(
              mapController: _mapController,
              currentLatLng: _myCurrentLatLng,
              alignment: Alignment.bottomRight,
            ),
            SaveLocationPluginOption(
              mapController: _mapController,
              currentLatLng: _currentLatLng,
              alignment: Alignment.bottomCenter,
            ),
            LoadingLocationPluginOption(
              mapController: _mapController,
              currentLatLng: _currentLatLng,
              alignment: Alignment.center,
            ),
            MarkerLayerOptions(markers: markers)
          ],
        ),
      ),
    );
    // return Column(

    //   children: [
    //     BlocListener<ElectricityLocationCurrentBloc, ElectricityLocationCurrentState>(
    //       listener: (context, state) {
    //         if (state is ElectricityLocationCurrentLoaded) {
    //           ElectricityLocationLatLongModel latLong = state.result;

    //           if (latLong != null) {
    //             _mapController.move(
    //               LatLng(
    //                 latLong.latitude,
    //                 latLong.longitude,
    //               ),
    //               _mapController.zoom,
    //             );

    //             setState(() {
    //               currentLatLng = LatLng(latLong.latitude, latLong.longitude);
    //               _currentMarkerLatLng = currentLatLng;
    //             });
    //           } else {
    //             _currentMarkerLatLng = LatLng(0, 0);
    //           }
    //         }
    //       },
    //       child: Container(
    //         height: deviceSize.height - 225,
    //         margin: EdgeInsets.zero,
    //         child: FlutterMap(
    //           mapController: _mapController,
    //           options: MapOptions(
    //             center: LatLng(_currentLatLng.latitude, _currentLatLng.longitude),
    //             zoom: 15,
    //             onTap: _handleTap,
    //             plugins: [
    //               CurrentLocationPlugin(),
    //               SaveLocationPlugin(),
    //               LoadingLocationPlugin(),
    //             ],
    //           ),
    //           layers: [
    //             TileLayerOptions(
    //               urlTemplate: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    //               subdomains: ['a', 'b', 'c'],
    //               tileProvider: NonCachingNetworkTileProvider(),
    //             ),
    //             CurrentLocationPluginOption(
    //               mapController: _mapController,
    //               currentLatLng: _myCurrentLatLng,
    //               alignment: Alignment.bottomRight,
    //             ),
    //             SaveLocationPluginOption(
    //               mapController: _mapController,
    //               currentLatLng: _currentLatLng,
    //               alignment: Alignment.bottomCenter,
    //             ),
    //             LoadingLocationPluginOption(
    //               mapController: _mapController,
    //               currentLatLng: _currentLatLng,
    //               alignment: Alignment.center,
    //             ),
    //             MarkerLayerOptions(markers: markers)
    //           ],
    //         ),
    //       ),
    //     ),
    //     // BlocListener<ElectricityLocationSaveBloc, ElectricityLocationSaveState>(
    //     //   listener: (context, state) {
    //     //     if (state is ElectricityLocationSaveLoaded) {
    //     //       if (state.saveSuccess != null && state.saveSuccess) {
    //     //         SweetAlert.show(
    //     //           context,
    //     //           subtitle: "บันทึกแผนที่สำเร็จ",
    //     //           style: SweetAlertStyle.success,
    //     //           showCancelButton: false,
    //     //           onPress: (bool isConfirm) {
    //     //             return true;
    //     //           },
    //     //         );
    //     //       } else if (state.saveSuccess != null && !state.saveSuccess) {
    //     //         SweetAlert.show(
    //     //           context,
    //     //           subtitle: "บันทึกแผนที่ไม่สำเร็จ",
    //     //           style: SweetAlertStyle.error,
    //     //         );
    //     //       }
    //     //     }
    //     //   },
    //     //   child: BlocBuilder<ElectricityLocationSaveBloc, ElectricityLocationSaveState>(
    //     //     builder: (context, state) {
    //     //       if (state is ElectricityLocationSaveLoading) {
    //     //         return Padding(
    //     //           padding: const EdgeInsets.only(top: 30),
    //     //           child: Loading(height: 20),
    //     //         );
    //     //       }

    //     //       return EmptyBox();
    //     //       // return Row(
    //     //       //   mainAxisAlignment: MainAxisAlignment.center,
    //     //       //   children: <Widget>[
    //     //       //     Container(
    //     //       //       padding: EdgeInsets.fromLTRB(0, 30, 0, 15),
    //     //       //       child: RaisedButton(
    //     //       //         padding: EdgeInsets.only(top: 12, left: 30, right: 30, bottom: 12),
    //     //       //         shape: RoundedRectangleBorder(
    //     //       //           borderRadius: BorderRadius.circular(7),
    //     //       //         ),
    //     //       //         child: Text(
    //     //       //           "บันทึก",
    //     //       //           style: TextStyle(
    //     //       //             fontWeight: FontWeight.w800,
    //     //       //             color: Colors.white,
    //     //       //             fontSize: 18,
    //     //       //           ),
    //     //       //         ),
    //     //       //         color: Color(AppData.yellowColor),
    //     //       //         onPressed: () {
    //     //       //           context.read<ElectricityLocationSaveBloc>().add(
    //     //       //                 ElectricityLocationSaveOnSubmit(
    //     //       //                   latitude: _currentLatLng.latitude,
    //     //       //                   longitude: _currentLatLng.longitude,
    //     //       //                 ),
    //     //       //               );
    //     //       //         },
    //     //       //       ),
    //     //       //     ),
    //     //       //   ],
    //     //       // );
    //     //     },
    //     //   ),
    //     // ),
    //   ],
    // );
  }

  void _handleTap(LatLng latlng) {
    print("_handleTap");
    print(latlng.latitude);
    print(latlng.longitude);
    setState(() {
      currentLatLng = latlng;
      _currentMarkerLatLng = latlng;
    });
  }

  void initLocationService() async {
    await _locationService.changeSettings(
      accuracy: LocationAccuracy.high,
      interval: 1000,
    );

    LocationData location;
    bool serviceEnabled;
    bool serviceRequestResult;
    PermissionStatus _permissionGranted;

    try {
      serviceEnabled = await _locationService.serviceEnabled();

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

        location = await _locationService.getLocation();
        _currentLocation = location;

        if (_currentLocation != null) {
          setState(() {
            _myCurrentLatLng = LatLng(
              _currentLocation.latitude,
              _currentLocation.longitude,
            );
          });

          if (currentLatLng == null) {
            _mapController.move(
              LatLng(
                _currentLocation.latitude,
                _currentLocation.longitude,
              ),
              _mapController.zoom,
            );
            setState(() {
              currentLatLng = LatLng(
                _currentLocation.latitude,
                _currentLocation.longitude,
              );
            });
          }
        }
      } else {
        serviceRequestResult = await _locationService.requestService();
        if (serviceRequestResult) {
          initLocationService();
          return;
        }
      }
    } on PlatformException catch (e) {
      print(e);
      if (e.code == 'PERMISSION_DENIED') {
        _serviceError = e.message;
      } else if (e.code == 'SERVICE_STATUS_ERROR') {
        _serviceError = e.message;
      }
      location = null;
    }
  }
}
