// ignore_for_file: dead_code
import 'package:echo_app/enums/customer-app-sign-up-field-type.dart';
import 'package:echo_app/enums/geographical-location-hierarchy-level.dart';
import 'package:echo_app/enums/global-errors.dart';
import 'package:echo_app/models/user.dart';
import 'package:echo_app/screens/sign_up/widgets/address.dart';
import 'package:echo_app/screens/sign_up/widgets/main.dart';
import 'package:echo_app/services/customer.service.dart';
import 'package:echo_app/services/non-operator-service.dart';
import 'package:echo_app/shared/core.session.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:material_segmented_control/material_segmented_control.dart';

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

// ignore: must_be_immutable
class SignUpPage extends StatefulWidget {
  @override
  _SignUpPageState createState() => _SignUpPageState();
}

class _SignUpPageState extends State<SignUpPage> {
  Map<int, Widget> _titles = {};
  Map<int, Widget> _children = {};
  int _currentSelection = 0;
  final GeolocatorPlatform _geolocatorPlatform = GeolocatorPlatform.instance;
  bool isCustomerNameMandatory = false;
  bool isPhoneNoMandatory = false;
  bool isTradeLicenseMandatory = false;
  bool isLocationHierarchyMandatory = false;
  bool isAddressLocationMandatory = false;
  bool isIdentificationMandatory = false;
  bool isEmailMandatory = false;

  UserModel signUpUser = new UserModel();

  var _nonOperatorService = new NonOperatorService();
  var _customerService = new CustomerService();
  var constPadding = EdgeInsets.symmetric(vertical: 5);

  initState() {
    if (CoreSession.locationHierarchyLevel <= 0) {
      getLocationHierarchy();
    }
    getSignUpFieldsData();
    _handlePermission();
    super.initState();
  }

  fillSegment() {
    setState(() {
      _titles = {
        0: Text("main".tr),
        // 2: Text("identification".tr),
      };
      _children = {
        0: Main(
          signUpUser,
          isCustomerNameMandatory,
          isPhoneNoMandatory,
          isTradeLicenseMandatory,
        ),
        1: Address(signUpUser, isLocationHierarchyMandatory,
            isAddressLocationMandatory),
        // 2: Identification(),
      };
    });
  }

  getSignUpFieldsData() async {
    EasyLoading.show(status: 'loading'.tr);
    var response = await _nonOperatorService.getcustomerAppSignUpFields();
    EasyLoading.dismiss();
    if (response['status'] == GlobalErrors.Success.index) {
      if (response['data'].length > 0) {
        CoreSession.signUpFields = response['data'];

        isCustomerNameMandatory = CoreSession.signUpFields.firstWhere(
                (element) =>
                    element['fieldId'] ==
                    CustomerAppSignUpFieldType
                        .CustomerName.index)['isMandatory'] ==
            true;

        isPhoneNoMandatory = CoreSession.signUpFields.firstWhere((element) =>
                element['fieldId'] ==
                CustomerAppSignUpFieldType.PhoneNo.index)['isMandatory'] ==
            true;

        isTradeLicenseMandatory = CoreSession.signUpFields.firstWhere(
                (element) =>
                    element['fieldId'] ==
                    CustomerAppSignUpFieldType
                        .TradeLicenseNo.index)['isMandatory'] ==
            true;

        isLocationHierarchyMandatory = CoreSession.signUpFields.firstWhere(
                (element) =>
                    element['fieldId'] ==
                    CustomerAppSignUpFieldType
                        .LocationHierarchy.index)['isMandatory'] ==
            true;

        isAddressLocationMandatory = CoreSession.signUpFields.firstWhere(
                (element) =>
                    element['fieldId'] ==
                    CustomerAppSignUpFieldType
                        .AddressLocation.index)['isMandatory'] ==
            true;
        isEmailMandatory = CoreSession.signUpFields.firstWhere(
                (element) =>
            element['fieldId'] ==
                CustomerAppSignUpFieldType
                    .Email.index)['isMandatory'] ==
            true;
        fillSegment();
      } else {
        CoreSession.signUpFields = [];
      }
    }
  }

  getLocationHierarchy() async {
    EasyLoading.show(status: 'loading'.tr);
    var response = await _nonOperatorService.getLocationHierarchy();
    if (response['status'] == GlobalErrors.Success.index) {
      CoreSession.fillLocationData(response);
    } else {
      EasyLoading.showError('error'.tr);
    }
    EasyLoading.dismiss();
  }

  void onSave() async {
    print(signUpUser);
    bool isValid = false;
    setState(() {
      isValid = _isValid();
    });
    if (isValid) {
      EasyLoading.show(status: 'loading'.tr);
      print(signUpUser);
      var response = await _customerService.createAccount(signUpUser);
      if (response['status'] == GlobalErrors.Success.index) {
        int customerId = response['data']['customerId'];
        int outletId = response['data']['outletId'];
        var response22 = await _customerService.uploadIdentifications(
            signUpUser.filesPath, signUpUser.filesName, customerId, outletId);
        print(response22);
        // if (this.identificationUrls && this.identificationUrls.length > 0) {
        //     this.uploadImages(res.data);
        // }
        EasyLoading.dismiss();
        EasyLoading.showSuccess("saved-successfully".tr);
        Navigator.pop(context);
      } else {
        EasyLoading.dismiss();
        EasyLoading.showError(response['message']);
      }
    }
  }

  bool _isValid() {
    bool invalidMainData = false;
    bool invalidAddressData = false;

    signUpUser.invalidCustomerName = false;
    signUpUser.invalidPhoneNumber = false;
    signUpUser.invalidUsername = false;
    signUpUser.invalidPassword = false;
    signUpUser.invalidRetypePassword = false;
    signUpUser.invalidTrade = false;
    signUpUser.passwordsNotMatch = false;

    signUpUser.invalidCountry = false;
    signUpUser.invalidState = false;
    signUpUser.invalidCity = false;
    signUpUser.invalidArea = false;
    signUpUser.invalidStreet = false;
    signUpUser.invalidAddress = false;

    if (signUpUser.customerName == '' && isCustomerNameMandatory) {
      signUpUser.invalidCustomerName = true;
      invalidMainData = true;
    }
    if (signUpUser.phoneNumber == '' && isPhoneNoMandatory) {
      signUpUser.invalidPhoneNumber = true;
      invalidMainData = true;
    }
    if (signUpUser.userName == '') {
      signUpUser.invalidUsername = true;
      invalidMainData = true;
    }
    if (signUpUser.password == '') {
      signUpUser.invalidPassword = true;
      invalidMainData = true;
    }
    if (signUpUser.retypePassword == '') {
      signUpUser.invalidRetypePassword = true;
      invalidMainData = true;
    }
    if (signUpUser.tradeLicenseNumber == '' && isTradeLicenseMandatory) {
      signUpUser.invalidTrade = true;
      invalidMainData = true;
    }
    if (signUpUser.password != '' &&
        signUpUser.retypePassword != '' &&
        signUpUser.password != signUpUser.retypePassword) {
      signUpUser.passwordsNotMatch = true;
      invalidMainData = true;
    }

    if (signUpUser.countryId == -1 &&
        CoreSession.locationHierarchyLevel >=
            GeographicalLocationHierarchyLevel.Country.index &&
        isLocationHierarchyMandatory) {
      signUpUser.invalidCountry = true;
      invalidAddressData = true;
    }
    if (signUpUser.stateId == -1 &&
        CoreSession.locationHierarchyLevel >=
            GeographicalLocationHierarchyLevel.State.index &&
        isLocationHierarchyMandatory) {
      signUpUser.invalidState = true;
      invalidAddressData = true;
    }
    if (signUpUser.cityId == -1 &&
        CoreSession.locationHierarchyLevel >=
            GeographicalLocationHierarchyLevel.City.index &&
        isLocationHierarchyMandatory) {
      signUpUser.invalidCity = true;
      invalidAddressData = true;
    }
    if (signUpUser.areaId == -1 &&
        CoreSession.locationHierarchyLevel >=
            GeographicalLocationHierarchyLevel.Area.index &&
        isLocationHierarchyMandatory) {
      signUpUser.invalidArea = true;
      invalidAddressData = true;
    }
    if (signUpUser.streetId == -1 &&
        CoreSession.locationHierarchyLevel >=
            GeographicalLocationHierarchyLevel.Street.index &&
        isLocationHierarchyMandatory) {
      signUpUser.invalidStreet = true;
      invalidAddressData = true;
    }
    if (signUpUser.address == '' && isAddressLocationMandatory) {
      signUpUser.invalidAddress = true;
      invalidAddressData = true;
    }
    // if (locationHierarchyController.text == '' &&
    //     isLocationHierarchyMandatory) {
    //   this.invalidLocationHierarchy = true;
    //   invalidAddressData = true;
    // }
    // if (addressLocationController.text == '' && isAddressLocationMandatory) {
    //   this.invalidAddressLocation = true;
    //   invalidAddressData = true;
    // }

    if (invalidMainData && _currentSelection == 0) {
      fillSegment();
    } else if (invalidAddressData && _currentSelection == 1) {
      fillSegment();
    } else if (invalidMainData && _currentSelection != 0) {
      _currentSelection = 0;
    } else if (invalidAddressData && _currentSelection != 1) {
      _currentSelection = 1;
    }

    return !invalidMainData && !invalidAddressData;
  }

  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;
  }

  @override
  Widget build(BuildContext context) {
     

    return Scaffold(
        bottomSheet: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Container(
            height: 50,
            child: ElevatedButton(
                style: TextButton.styleFrom(
                  padding: EdgeInsets.only(right: 30, left: 30),
                  alignment: Alignment.centerLeft,
                  backgroundColor: Variables.color_primary,
                  shape: const RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(50))),
                ),
                onPressed: () {
                  if (_currentSelection == 0){
                    _currentSelection = 1;
                    setState(() {

                    });
                  }else
                    setState(() {
                      onSave();
                    });
                },
                child: Center(
                  child: Text(
                    _currentSelection== 0 ?"Next".tr:"create-account".tr,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 18,
                    ),
                  ),
                )),
          ),
        ),
      body: SingleChildScrollView(
        child: Container(
          height: MediaQuery.of(context).size.height ,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: (_children.length > 0)
                ? [
                    // Expanded(
                    //   flex: 1,
                    //   child: Container(
                    //     child: MaterialSegmentedControl(
                    //       children: _titles,
                    //       selectionIndex: _currentSelection,
                    //       borderColor: Variables.color_primary,
                    //       selectedColor: Variables.color_primary,
                    //       unselectedColor: Colors.white,
                    //       borderRadius: 10,
                    //       verticalOffset: 0,
                    //       disabledChildren: [
                    //         3,
                    //       ],
                    //       onSegmentChosen : (int index) {
                    //         setState(() {
                    //           _currentSelection = index;
                    //         });
                    //       },
                    //     ),
                    //   ),
                    // ),
                    Padding(
                      padding: const EdgeInsets.symmetric(vertical: 15.0),
                      child: Row(
                        children: [
                          IconButton(
                            icon: Icon(Icons.arrow_back,color: Variables.color_primary,),
                            onPressed: () {
                              Navigator.of(context).pop();
                          }),
                        ],
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 20,vertical: 5),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text("Create Account", style: TextStyle(color: Colors.black,fontSize: 24,fontWeight: FontWeight.bold)),
                          Text("Let’s create your account on Echo", style: TextStyle(color: Colors.grey,fontSize: 14)),

                        ],
                      ),
                    ),
                    Expanded(
                      flex: 9,
                      // child: SingleChildScrollView(
                      child: Container(
                        padding: EdgeInsets.symmetric(horizontal: 15),
                        child: _children[_currentSelection],
                      ),
                      // ),
                    ),
                  ]
                : [],
          ),
        ),
      ),

    );
  }
}
