import 'package:dropdown_search/dropdown_search.dart';
import 'package:e_commerce_training/res/R.dart';
import 'package:e_commerce_training/src/model/repository/app_repository.dart';
import 'package:e_commerce_training/src/model/response/city_response.dart';
import 'package:e_commerce_training/src/model/response/district_response.dart';
import 'package:e_commerce_training/src/model/response/ward_response.dart';
import 'package:e_commerce_training/src/page/profile/profile_cubit.dart';
import 'package:e_commerce_training/src/util/util.dart';
import 'package:e_commerce_training/src/widget/pending_action.dart';
import 'package:e_commerce_training/src/widget/text_field_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:easy_localization/easy_localization.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({Key? key}) : super(key: key);

  @override
  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  TextEditingController _nameController = TextEditingController();
  TextEditingController _phoneNumberController = TextEditingController();
  TextEditingController _emailController = TextEditingController();
  TextEditingController birthDayController = TextEditingController();
  TextEditingController _customerAddressController = TextEditingController();
  TextEditingController _introduceController = TextEditingController();
  TextEditingController _currentPasswordController = TextEditingController();
  TextEditingController _newPasswordController = TextEditingController();
  TextEditingController _rePasswordController = TextEditingController();
  late String _errorCurrentPass, _errorNewPass, _errorRePass;
  late ProfileCubit _cubit;
  RefreshController _refreshController = RefreshController();
  FocusNode _nameFocus = FocusNode();
  FocusNode _phoneNumberFocus = FocusNode();
  FocusNode _emailFocus = FocusNode();
  FocusNode _customerAddressFocus = FocusNode();
  FocusNode _introduceFocus = FocusNode();
  FocusNode _currentPasswordFocus = FocusNode();
  FocusNode _newPasswordFocus = FocusNode();
  FocusNode _rePasswordFocus = FocusNode();
  FocusNode _birthDayFocus = FocusNode();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    AppRepository repository = AppRepository();
    _cubit = ProfileCubit(repository);
    _cubit.getDetailUser();
    _cubit.getCity();
    _nameController.text = _cubit.fullName;
    _phoneNumberController.text = _cubit.phoneNumber;
    _emailController.text = _cubit.email;
    _cubit.shippingCityName;
    _cubit.shippingDistrictName;
    _cubit.shippingWardName;
    _cubit.shippingAddress;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: R.color.primaryColor,
        title: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
                child: Center(
                    child: Text(
              R.string.profile.tr(),
              style: TextStyle(fontSize: 20.sp),
            ))),
            InkWell(
              child: Text(
                R.string.save.tr(),
                style: TextStyle(fontSize: 16.sp),
              ),
              onTap: () {
                _cubit.updateProfile(
                    fullName: _nameController.text,
                    phoneNumber: _phoneNumberController.text,
                    email: _emailController.text,
                    shippingAddress: _customerAddressController.text);
                // TODO Update profile
              },
            ),
          ],
        ),
      ),
      body: BlocProvider(
        create: (BuildContext context) => _cubit,
        child: BlocConsumer<ProfileCubit, ProfileState>(
          listener: (context, state) {
            if (state is ProfileFailure) Util.showErrorSnackBar(context, state.error);
            if (!(state is ProfileLoading)) _refreshController.refreshCompleted();
            if (state is GetProfileSuccess) {
              // TODO set profile field first time
              _nameController.text = _cubit.fullName;
            }
          },
          builder: (context, state) {
            return GestureDetector(
              onTap: () => Util.hideKeyboard(context),
              child: Stack(
                children: [
                  SingleChildScrollView(
                    child: Padding(
                      padding: EdgeInsets.symmetric(vertical: 15, horizontal: 15),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          buildInputCustomerName(context),
                          SizedBox(
                            height: 15,
                          ),
                          buildInputPhoneNumber(context),
                          SizedBox(
                            height: 15,
                          ),
                          buildInputEmail(context),
                          SizedBox(
                            height: 15,
                          ),
                          buildDropdownCity(context),
                          SizedBox(
                            height: 15,
                          ),
                          buildDropdownDistrict(context),
                          SizedBox(
                            height: 15,
                          ),
                          buildDropdownWard(context),
                          SizedBox(
                            height: 10,
                          ),
                          buildInputCustomerAddress(context),
                        ],
                      ),
                    ),
                  ),
                  Visibility(
                    visible: state is ProfileLoading,
                    child: PendingAction(),
                  ),
                ],
              ),
            );
          },
        ),
      ),
    );
  }

  Widget buildInputCustomerName(BuildContext context) {
    return TextFieldWidget(
      autoFocus: false,
      controller: _nameController,
      textInputAction: TextInputAction.next,
      labelText: R.string.name.tr(),
      hintText: R.string.input_name.tr(),
      keyboardType: TextInputType.text,
      errorText: _cubit.errorName,
      focusNode: _nameFocus,
      onChanged: (text) => _cubit.validateName,
      onSubmitted: (text) => Util.navigateNextFocusChange(context, _nameFocus, _phoneNumberFocus),
    );
  }

  Widget buildInputPhoneNumber(BuildContext context) {
    return TextFieldWidget(
      autoFocus: false,
      controller: _phoneNumberController,
      textInputAction: TextInputAction.next,
      labelText: R.string.phone_number.tr(),
      hintText: R.string.input_phone_number.tr(),
      keyboardType: TextInputType.phone,
      errorText: _cubit.errorPhone,
      onChanged: (text) => _cubit.validatePhoneNumber,
      focusNode: _phoneNumberFocus,
      onSubmitted: (text) {
        Util.navigateNextFocusChange(context, _phoneNumberFocus, _nameFocus);
      },
    );
  }

  Widget buildInputEmail(BuildContext context) {
    return TextFieldWidget(
        autoFocus: false,
        controller: _emailController,
        textInputAction: TextInputAction.next,
        labelText: R.string.email.tr(),
        hintText: R.string.input_email.tr(),
        keyboardType: TextInputType.emailAddress,
        errorText: _cubit.errorEmail,
        focusNode: _emailFocus,
        onChanged: (text) => _cubit.validateEmail,
        onSubmitted: (text) => Util.navigateNextFocusChange(context, _emailFocus, _nameFocus));
  }

  Widget buildDropdownCity(BuildContext context) {
    return DropdownSearch<CityData>(
      hint: R.string.please_enter_city.tr(),
      mode: Mode.MENU,
      items: _cubit.listCity,
      label: R.string.city.tr(),
      selectedItem: _cubit.selectedCity,
      dropdownSearchBaseStyle: TextStyle(fontSize: 16.sp, color: R.color.black),
      onFind: (String? filter) async => _cubit.searchCity(filter),
      itemAsString: (CityData? data) => data?.cityName ?? _cubit.shippingCityName,
      onChanged: (CityData? data) => _cubit.selectCity(data),
    );
  }

  Widget buildDropdownDistrict(BuildContext context) {
    return DropdownSearch<DistrictData>(
      hint: R.string.please_enter_district.tr(),
      mode: Mode.MENU,
      items: _cubit.listDistrict,
      label: R.string.district.tr(),
      selectedItem: _cubit.selectedDistrict,
      dropdownSearchBaseStyle: TextStyle(fontSize: 16.sp, color: R.color.black),
      onFind: (String? filter) async => _cubit.searchDistrict(filter),
      itemAsString: (DistrictData? data) => data?.districtName ?? _cubit.shippingDistrictName,
      onChanged: (DistrictData? data) => _cubit.selectDistrict(data),
    );
  }

  Widget buildDropdownWard(BuildContext context) {
    return DropdownSearch<WardData>(
      hint: R.string.please_enter_ward.tr(),
      mode: Mode.MENU,
      items: _cubit.listWard,
      label: R.string.ward.tr(),
      selectedItem: _cubit.selectedWard,
      dropdownSearchBaseStyle: TextStyle(fontSize: 16.sp, color: R.color.black),
      onFind: (String? filter) async => _cubit.searchWard(filter),
      itemAsString: (WardData? data) => data?.wardName ?? _cubit.shippingWardName,
      onChanged: (WardData? data) => _cubit.selectWard(data),
    );
  }

  Widget buildInputCustomerAddress(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 4),
      child: TextFieldWidget(
          autoFocus: false,
          controller: _customerAddressController,
          textInputAction: TextInputAction.done,
          keyboardType: TextInputType.text,
          labelText: R.string.detail_address.tr(),
          hintText: R.string.please_detail_address.tr(),
          focusNode: _customerAddressFocus,
          onSubmitted: (text) => _customerAddressFocus.unfocus()),
    );
  }
}
