import 'package:echo_app/enums/global-errors.dart';
import 'package:echo_app/models/operator.dart';
import 'package:echo_app/screens/my_order/my_order.page.dart';
import 'package:echo_app/screens/notifications/notification.page.dart';
import 'package:echo_app/services/general.service.dart';
import 'package:echo_app/shared/core.session.dart';
import 'package:echo_app/widgets/general_text_form_field.widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';

import '../../theme/variables.dart';

// ignore: must_be_immutable
class ProfileEditPage extends StatefulWidget {
  var addressText = '';
  var phoneText = '';
  var currentLocation = '';

  ProfileEditPage(this.addressText, this.phoneText, this.currentLocation);

  @override
  State<ProfileEditPage> createState() => _ProfileEditPageState();
}

class _ProfileEditPageState extends State<ProfileEditPage> {
  TextEditingController phoneController = TextEditingController();
  TextEditingController addressController = TextEditingController();
  TextEditingController currentLocationController = TextEditingController();
  initState() {
    super.initState();
    addressController.text = widget.addressText;
    phoneController.text = widget.phoneText;
    currentLocationController.text = widget.currentLocation;
  }

  var myPosition;
  GeneralService _generalService = new GeneralService();

  var constPadding = EdgeInsets.fromLTRB(0, 5, 0, 10);

  var operatorCustomerModel = new OperatorCustomerModel();
  final GeolocatorPlatform _geolocatorPlatform = GeolocatorPlatform.instance;

  String errorMesage = '';

  bool loading = false;

  _updateProfileData(
      OperatorCustomerModel operatorCustomerModel, context) async {
    EasyLoading.show(status: 'loading'.tr);
    var respose =
        await this._generalService.updateProfileData(operatorCustomerModel);
    if (respose['status'] == GlobalErrors.Success.index) {
      loading = false;
      EasyLoading.dismiss();
      EasyLoading.showSuccess("saved-successfully".tr);
      Navigator.pop(context);
    } else {
      loading = false;
      EasyLoading.dismiss();
      EasyLoading.showError("error".tr);
    }
  }

  Future<bool> _handlePermission() async {
    bool serviceEnabled;
    LocationPermission permission;

    // Test if location services are enabled.
    serviceEnabled = await _geolocatorPlatform.isLocationServiceEnabled();
    if (!serviceEnabled) {
      return false;
    }

    permission = await _geolocatorPlatform.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await _geolocatorPlatform.requestPermission();
      if (permission == LocationPermission.denied) {
        return false;
      }
    }

    if (permission == LocationPermission.deniedForever) {
      return false;
    }

    return true;
  }

  Future<void> _getCurrentPosition() async {
    final hasPermission = await _handlePermission();

    if (!hasPermission) {
      return;
    }
    LocationSettings settings =
        new LocationSettings(accuracy: LocationAccuracy.bestForNavigation);

    final position = await _geolocatorPlatform.getCurrentPosition(
        locationSettings: settings);
    this.myPosition = position;
    this.currentLocationController.text =
        this.myPosition.latitude.toString() +
            "," +
            this.myPosition.longitude.toString();
    print(this.currentLocationController.text);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Row(
          children: [
            IconButton(
                icon: Icon(Icons.arrow_back,color: Colors.black,),
                onPressed: () {
                  Navigator.pop(context);
                }),
            Text("edit-profile".tr,style: TextStyle(color: Colors.black),),
            Spacer(),
            CoreSession.newNotificationCount > 0 ?
            IconButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => NotificationPage()),
                  );
                },
                icon: Image.asset(
                    'assets/imgs/more_icons/notification.png',
                    color: Variables.color_primary,
                    height: 33,
                    width: 30))
                :     IconButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => NotificationPage()),
                  );
                },
                icon: Image.asset(
                    'assets/imgs/more_icons/notification.png',
                    color: Variables.color_primary,
                    height: 33,
                    width: 30)),
            IconButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => MyOrderPage()),
                  );
                },
                icon: Image.asset(
                    'assets/imgs/default/cart.png',
                    color: Variables.color_primary,
                    height: 33,
                    width: 30)),
          ],
        ),
        automaticallyImplyLeading: false,),
      body: SingleChildScrollView(
        child: Form(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 10),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                if (errorMesage != '')
                  Container(
                    padding: EdgeInsets.only(top: 5),
                    child: Text(
                      errorMesage,
                      style: TextStyle(color: Colors.red),
                      textAlign: TextAlign.center,
                    ),
                  ),
                GeneralTextFormFieldWidget(
                    "phone",
                    this.phoneController,
                    false,
                    null,
                    true,
                    false,
                    null,
                    null,
                    null,
                    this.constPadding,
                    null,
                    1,
                    true,
                    false,
                    false,
                    15,
                    TextInputType.phone),
                GeneralTextFormFieldWidget(
                    "address",
                    this.addressController,
                    false,
                    null,
                    true,
                    false,
                    null,
                    null,
                    null,
                    this.constPadding,
                    null,
                    1,
                    true,
                    false,
                    false,
                    15,
                    TextInputType.text),
                Container(
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Expanded(
                          flex: 5,
                          child: GeneralTextFormFieldWidget(
                              "current-location",
                              this.currentLocationController,
                              false,
                              null,
                              false,
                              false,
                              null,
                              null,
                              null,
                              this.constPadding,
                              null,
                              1,
                              true,
                              false,
                              false,
                              15,
                              TextInputType.text),
                        ),
                        Expanded(
                          child: Padding(
                            padding: EdgeInsets.symmetric(horizontal: 2),
                            child: IconButton(
                              icon: Icon(
                                Icons.gps_fixed,
                                color: Variables.color_primary,
                              ),
                              onPressed: () {
                                _getCurrentPosition();
                              },
                            ),
                          ),
                        )
                      ]),
                )
              ],
            ),
          ),
        ),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
      floatingActionButton: Container(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Container(
              padding: this.constPadding,
              child: FloatingActionButton(
                backgroundColor: Colors.redAccent,
                child: Icon(Icons.close),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 1),
              child: FloatingActionButton(
                backgroundColor: Colors.lightGreen,
                child: Icon(Icons.done),
                onPressed: () {
                  var phone = this.phoneController.text;
                  var address = this.addressController.text;
                  //var location = currentLocationController.text;
                  setState(() {
                    if (phone == '' || address == '') {
                      //|| location == ''
                      errorMesage = 'fill-data'.tr;
                    } else {
                      operatorCustomerModel.phone = phone;
                      operatorCustomerModel.address = address;
                      operatorCustomerModel.latitude = -1;
                      operatorCustomerModel.longitude = -1;
                      if (this.myPosition != null) {
                        operatorCustomerModel.latitude =
                            this.myPosition.latitude;
                        operatorCustomerModel.longitude =
                            this.myPosition.longitude;
                      }

                      //var coords = location.split(',');
                      // if (coords.length == 2) {
                      //   operatorCustomerModel.latitude =
                      //       double.parse(coords[0]);
                      //   operatorCustomerModel.longitude =
                      //       double.parse(coords[1]);
                      // }
                      if (!loading) {
                        loading = true;
                        _updateProfileData(operatorCustomerModel, context);
                      }
                    }
                  });
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
