import 'package:echo_app/enums/geographical-location-hierarchy-level.dart';
import 'package:echo_app/models/user.dart';
import 'package:echo_app/shared/core.session.dart';
import 'package:echo_app/widgets/general_dropdown_button.widget.dart';
import 'package:echo_app/widgets/general_text_form_field.widget.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';

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

// ignore: must_be_immutable
class Address extends StatefulWidget {
  final bool isLocationHierarchyMandatory;
  final bool isAddressLocationMandatory;
  final UserModel signUpUser;

  Address(this.signUpUser, this.isLocationHierarchyMandatory,
      this.isAddressLocationMandatory);
  @override
  State<Address> createState() => _AddressState();
}

class _AddressState extends State<Address> {
  final TextEditingController addressController = new TextEditingController();
  TextEditingController currentLocationController = TextEditingController();
  final GeolocatorPlatform _geolocatorPlatform = GeolocatorPlatform.instance;
  var myPosition;

  final addressNode = FocusNode();

  var constMargin = EdgeInsets.only(bottom: 10);
  var countries = [];
  var states = [];
  var cities = [];
  var areas = [];
  var streets = [];

  bool isFullBorder = true;

  // ignore: unused_field
  bool _isAddress = false;
  // ignore: unused_field
  bool _isDeliveryLocation = false;

  @override
  void initState() {
    fillFirstList();
    super.initState();
  }

  fillFirstList() {
    countries = [];
    states = [];
    cities = [];
    areas = [];
    streets = [];

    if (CoreSession.locationHierarchyLevel ==
        GeographicalLocationHierarchyLevel.Country.index) {
      countries = CoreSession.countries;
    }
    if (CoreSession.locationHierarchyLevel ==
        GeographicalLocationHierarchyLevel.State.index) {
      states = CoreSession.states;
    }
    if (CoreSession.locationHierarchyLevel ==
        GeographicalLocationHierarchyLevel.City.index) {
      cities = CoreSession.cities;
    }
    if (CoreSession.locationHierarchyLevel ==
        GeographicalLocationHierarchyLevel.Area.index) {
      areas = CoreSession.areas;
    }
    if (CoreSession.locationHierarchyLevel ==
        GeographicalLocationHierarchyLevel.Street.index) {
      streets = CoreSession.streets;
    }
  }

  @override
  didUpdateWidget(Address oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  onChangeCountry(id) {
    setState(() {
      widget.signUpUser.countryId = id;
      widget.signUpUser.stateId = -1;
      widget.signUpUser.cityId = -1;
      widget.signUpUser.areaId = -1;
      widget.signUpUser.streetId = -1;

      if (widget.isLocationHierarchyMandatory) {
        if (id == null || id == '' || id == -1) {
          widget.signUpUser.invalidCountry = true;
        } else {
          widget.signUpUser.invalidCountry = false;
        }
      }
      states = [];
      cities = [];
      areas = [];
      streets = [];

      if (CoreSession.states.any((element) => element['countryId'] == id)) {
        states = CoreSession.states
            .where((element) => element['countryId'] == id)
            .toList();
      }
    });
  }

  onChangeState(id) {
    setState(() {
      widget.signUpUser.stateId = id;
      widget.signUpUser.cityId = -1;
      widget.signUpUser.areaId = -1;
      widget.signUpUser.streetId = -1;

      if (widget.isLocationHierarchyMandatory) {
        if (id == null || id == '' || id == -1) {
          widget.signUpUser.invalidState = true;
        } else {
          widget.signUpUser.invalidState = false;
        }
      }
      cities = [];
      areas = [];
      streets = [];

      if (CoreSession.cities.any((element) => element['stateId'] == id)) {
        cities = CoreSession.cities
            .where((element) => element['stateId'] == id)
            .toList();
      }
    });
  }

  onChangeCity(id) {
    setState(() {
      widget.signUpUser.cityId = id;
      widget.signUpUser.areaId = -1;
      widget.signUpUser.streetId = -1;
      if (widget.isLocationHierarchyMandatory) {
        if (id == null || id == '' || id == -1) {
          widget.signUpUser.invalidCity = true;
        } else {
          widget.signUpUser.invalidCity = false;
        }
      }

      areas = [];
      streets = [];

      if (CoreSession.areas.any((element) => element['cityId'] == id)) {
        areas = CoreSession.areas
            .where((element) => element['cityId'] == id)
            .toList();
      }
    });
  }

  onChangeArea(id) {
    setState(() {
      widget.signUpUser.areaId = id;
      widget.signUpUser.streetId = -1;
      if (widget.isLocationHierarchyMandatory) {
        if (id == null || id == '' || id == -1) {
          widget.signUpUser.invalidArea = true;
        } else {
          widget.signUpUser.invalidArea = false;
        }
      }
      streets = [];

      if (CoreSession.streets.any((element) => element['areaId'] == id)) {
        streets = CoreSession.streets
            .where((element) => element['areaId'] == id)
            .toList();
      }
    });
  }

  onChangeStreet(id) {
    setState(() {
      widget.signUpUser.streetId = id;

      if (widget.isLocationHierarchyMandatory) {
        if (id == null || id == '' || id == -1) {
          widget.signUpUser.invalidStreet = true;
        } else {
          widget.signUpUser.invalidStreet = false;
        }
      }
    });
  }
  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);
    this.widget.signUpUser.latitude = this.myPosition.latitude;
    this.widget.signUpUser.longitude = this.myPosition.longitude;
  }
  @override
  Widget build(BuildContext context) {
    fillFirstList();
    addressController.text = widget.signUpUser.address;

    if (widget.signUpUser.countryId != -1 &&
        CoreSession.locationHierarchyLevel >=
            GeographicalLocationHierarchyLevel.Country.index) {
      if (CoreSession.states.any(
          (element) => element['countryId'] == widget.signUpUser.countryId)) {
        states = CoreSession.states
            .where((element) =>
                element['countryId'] == widget.signUpUser.countryId)
            .toList();
      }
    }
    if (widget.signUpUser.stateId != -1 &&
        CoreSession.locationHierarchyLevel >=
            GeographicalLocationHierarchyLevel.State.index) {
      if (CoreSession.cities
          .any((element) => element['stateId'] == widget.signUpUser.stateId)) {
        cities = CoreSession.cities
            .where((element) => element['stateId'] == widget.signUpUser.stateId)
            .toList();
      }
    }
    if (widget.signUpUser.cityId != -1 &&
        CoreSession.locationHierarchyLevel >=
            GeographicalLocationHierarchyLevel.City.index) {
      if (CoreSession.areas
          .any((element) => element['cityId'] == widget.signUpUser.cityId)) {
        areas = CoreSession.areas
            .where((element) => element['cityId'] == widget.signUpUser.cityId)
            .toList();
      }
    }
    if (widget.signUpUser.areaId != -1 &&
        CoreSession.locationHierarchyLevel >=
            GeographicalLocationHierarchyLevel.Area.index) {
      if (CoreSession.streets
          .any((element) => element['areaId'] == widget.signUpUser.areaId)) {
        streets = CoreSession.streets
            .where((element) => element['areaId'] == widget.signUpUser.areaId)
            .toList();
      }
    }

    //  _onSubmitCustomerName() {
    //   FocusScope.of(context).requestFocus(_phoneNumber);
    // }

    _onAddressValueChanged(value) {
      widget.signUpUser.address = value;
      if (value == '' && widget.isAddressLocationMandatory) {
        widget.signUpUser.invalidAddress = true;
      } else {
        widget.signUpUser.invalidAddress = false;
      }
    }

    print('rebuild');

    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          //countries
          if (CoreSession.locationHierarchyLevel >=
              GeographicalLocationHierarchyLevel.Country.index)
            GeneralDropdownButtonWidget(
                countries,
                'countryName',
                'countryId',
                constMargin,
                widget.signUpUser.countryId == -1
                    ? null
                    : widget.signUpUser.countryId,
                onChangeCountry,
                CoreSession.Desc_Geographical_Location_Name_Five,
                widget.isLocationHierarchyMandatory,
                widget.signUpUser.invalidCountry,
                isFullBorder),

          //states
          if (CoreSession.locationHierarchyLevel >=
              GeographicalLocationHierarchyLevel.State.index)
            GeneralDropdownButtonWidget(
                states,
                'statessName',
                'stateId',
                constMargin,
                widget.signUpUser.stateId == -1
                    ? null
                    : widget.signUpUser.stateId,
                onChangeState,
                CoreSession.Desc_Geographical_Location_Name_Four,
                widget.isLocationHierarchyMandatory,
                widget.signUpUser.invalidState,
                isFullBorder),
          //cities
          if (CoreSession.locationHierarchyLevel >=
              GeographicalLocationHierarchyLevel.City.index)
            GeneralDropdownButtonWidget(
                cities,
                'cityName',
                'cityId',
                constMargin,
                widget.signUpUser.cityId == -1 ? null : widget.signUpUser.cityId,
                onChangeCity,
                CoreSession.Desc_Geographical_Location_Name_Three,
                widget.isLocationHierarchyMandatory,
                widget.signUpUser.invalidCity,
                isFullBorder),
          //areas
          if (CoreSession.locationHierarchyLevel >=
              GeographicalLocationHierarchyLevel.Area.index)
            GeneralDropdownButtonWidget(
                areas,
                'areaName',
                'areaId',
                constMargin,
                widget.signUpUser.areaId == -1 ? null : widget.signUpUser.areaId,
                onChangeArea,
                CoreSession.Desc_Geographical_Location_Name_Two,
                widget.isLocationHierarchyMandatory,
                widget.signUpUser.invalidArea,
                isFullBorder),
          //streets
          if (CoreSession.locationHierarchyLevel >=
              GeographicalLocationHierarchyLevel.Street.index)
            GeneralDropdownButtonWidget(
                streets,
                'streetName',
                'streetId',
                constMargin,
                widget.signUpUser.streetId == -1
                    ? null
                    : widget.signUpUser.streetId,
                onChangeStreet,
                CoreSession.Desc_Geographical_Location_Name_One,
                widget.isLocationHierarchyMandatory,
                widget.signUpUser.invalidStreet,
                isFullBorder),

          GeneralTextFormFieldWidget(
              "address",
              addressController,
              widget.isAddressLocationMandatory,
              '',
              true,
              false,
              null,
              null, //_onSubmitAddress,
              _onAddressValueChanged,
              constMargin,
              addressNode,
              1,
              true,
              widget.signUpUser.invalidAddress,
              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,
                        EdgeInsets.fromLTRB(0, 5, 0, 10),
                        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();
                        },
                      ),
                    ),
                  )
                ]),
          ),
        ],
      ),
    );
  }
}
