import 'package:injectable/injectable.dart';
import 'package:keyboard/base/base_controller.dart';
import 'package:get/get.dart';
import 'package:keyboard/data/repository/account_repository.dart';
import 'package:keyboard/data/repository/keyboard_repository.dart';

import '../../data/api/response/user_info_response.dart';
import '../../data/bean/default_avatar_info.dart';
import '../../data/repository/config_repository.dart';
import '../../resource/string.gen.dart';
import '../../utils/age_zodiac_sign_util.dart';
import '../../utils/atmob_log.dart';
import '../../utils/error_handler.dart';
import '../../utils/http_handler.dart';
import '../../utils/toast_util.dart';
import '../change/birthday/change_birthday_page.dart';
import '../change/gender/change_gender_page.dart';
import '../change/nickname/change_nickname_page.dart';
import 'package:intl/intl.dart';

@injectable
class UserProfileController extends BaseController {
  final tag = "UserProfileController";

  final ConfigRepository configRepository;

  final AccountRepository accountRepository;

  final KeyboardRepository keyboardRepository;


  final RxList<String> _girlAvatars = <String>[].obs;

  final RxList<String> _boyAvatars = <String>[].obs;

  final RxString _userAvatarUrl = "".obs;

  String get userAvatarUrl => _userAvatarUrl.value;

  final RxnInt _currentGender = RxnInt(null);

  int? get currentGender => _currentGender.value;

  final Rxn<String> _currentBirthday = Rxn<String>(null);

  String? get currentBirthday => _currentBirthday.value;

  final RxnString _currentNickname = RxnString(null);

  String? get currentNickname => _currentNickname.value;

  String? get phone => accountRepository.loginPhoneNum.value;

  bool get isLogin => accountRepository.isLogin.value;

  UserInfoResponse? get userInfo => accountRepository.userInfo.value;

  Rxn<DefaultAvatarInfo> get currentDefaultAvatarInfo =>
      configRepository.defaultAvatarInfo;

  UserProfileController(this.configRepository, this.accountRepository,this.keyboardRepository);

  @override
  void onInit() {
    super.onInit();
    _currentNickname.value = userInfo?.name;
    _currentBirthday.value = AgeZodiacSignUtil.formatBirthdayFromString(
      userInfo?.birthday,
    );
    _currentGender.value = userInfo?.gender;
    _userAvatarUrl.value = userInfo?.imageUrl ?? "";
    updateAvatarListsAndSelectFirst(configRepository.defaultAvatarInfo.value);
  }

  void clickBack() {
    Get.back();
  }

  void updateAvatarListsAndSelectFirst(DefaultAvatarInfo? info) {
    _boyAvatars.assignAll(info?.maleAvatars ?? []);
    _girlAvatars.assignAll(info?.femaleAvatars ?? []);
    if (_userAvatarUrl.isNotEmpty) {
      return;
    }
    if (_currentGender.value == 1) {
      _userAvatarUrl.value = _boyAvatars.isNotEmpty ? _boyAvatars.first : "";
    } else {
      _userAvatarUrl.value = _girlAvatars.isNotEmpty ? _girlAvatars.first : "";
    }
  }

  void nextAvatar() {
    AtmobLog.d(tag, "nextAvatar");

    if (_currentGender.value == 1) {
      int currentIndex = _boyAvatars.indexOf(_userAvatarUrl.value);
      _userAvatarUrl.value =
          _boyAvatars[(currentIndex + 1) % _boyAvatars.length];
    } else {
      int currentIndex = _girlAvatars.indexOf(_userAvatarUrl.value);
      _userAvatarUrl.value =
          _girlAvatars[(currentIndex + 1) % _girlAvatars.length];
    }
    _settingUseInfo();

  }

  void clickBirthday() async {
    AtmobLog.d(tag, 'clickBirthday');
    final result = await ChangeBirthdayPage.start(
      birthday: _currentBirthday.value,
    );
    if (result != null) {
      AtmobLog.d(tag, 'clickBirthday result: $result');
      _currentBirthday.value = result;
      _settingUseInfo();
    }
  }

  String getUserName() {
    if (isLogin && phone != null && phone!.length > 4) {
      return '${StringName.mineAccountLoggedDesc}${phone!.substring(phone!.length - 4)}';
    } else {
      return StringName.mineAccountNoLogin;
    }
  }

  void clickGender() async {
    AtmobLog.d(tag, 'clickGender');
    final result = await ChangeGenderPage.start(gender: _currentGender.value);
    if (result != null) {
      _currentGender.value = result;
    }

    if (result == 1 && _boyAvatars.isNotEmpty) {
      _userAvatarUrl.value = _boyAvatars.first;
      _settingUseInfo();
    } else if (_girlAvatars.isNotEmpty) {
      _userAvatarUrl.value = _girlAvatars.first;
      _settingUseInfo();
    } else {
      _userAvatarUrl.value = "";
    }
  }

  void clickNickname() async {
    AtmobLog.d(tag, 'clickNickname');
    final result = await ChangeNicknamePage.start(
      nickName: _currentNickname.value,
    );
    if (result != null) {
      _currentNickname.value = result;
      _settingUseInfo();
    }
  }

  Future<void> _settingUseInfo() async {
    await Future.delayed(const Duration(milliseconds: 300));
    try {
     await accountRepository.setUserInfo(
        name: _currentNickname.value,
        birthday:
        _currentBirthday.value,
        gender: _currentGender.value,
        imageUrl: _userAvatarUrl.value,
      );
      await Future.delayed(const Duration(milliseconds: 300));
      accountRepository.refreshUserInfo();
      keyboardRepository.refreshData();
    } catch (error) {
      if (error is ServerErrorException) {
        ToastUtil.show(error.message);
      } else {
        ErrorHandler.toastError(error);
      }
    }
  }



  String get genderText {
    if (_currentGender.value == 1) return '男';
    if (_currentGender.value == 2) return '女';
    return '请选择';
  }
}
