import 'package:get/get.dart';
import 'package:injectable/injectable.dart';
import 'package:keyboard/base/base_controller.dart';
import 'package:keyboard/data/bean/default_avatar_info.dart';
import 'package:keyboard/data/bean/keyboard_info.dart';
import 'package:keyboard/data/repository/keyboard_repository.dart';
import 'package:keyboard/dialog/loading_dialog.dart';
import 'package:keyboard/module/change/gender/change_gender_page.dart';
import 'package:keyboard/utils/age_zodiac_sign_util.dart';
import 'package:keyboard/utils/atmob_log.dart';
import 'package:keyboard/utils/toast_util.dart';

import '../../../data/bean/character_info.dart';
import '../../../data/repository/config_repository.dart';
import '../../../resource/assets.gen.dart';
import '../../../utils/error_handler.dart';
import '../../../utils/http_handler.dart';
import '../../change/birthday/change_birthday_page.dart';
import '../../change/nickname/change_nickname_page.dart';
import '../../keyboard_manage/keyboard_manage_page.dart';

enum ProfileEditMode {
  add, // 新增
  edit, // 编辑
}

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

  final ConfigRepository configRepository;

  final KeyboardRepository keyboardRepository;

  final RxnInt _currentGender = RxnInt(null);

  final RxString _avatarUrl = "".obs;

  String get avatarUrl => _avatarUrl.value;

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

  late final ProfileEditMode mode;

  bool get isEditMode => mode == ProfileEditMode.edit;

  bool get isAddMode => mode == ProfileEditMode.add;

  final Rx<KeyboardInfo> _currentCustomKeyboardInfo = KeyboardInfo().obs;

  Rx<KeyboardInfo> get currentCustomKeyboardInfo => _currentCustomKeyboardInfo;

  final RxnString _currentBirthday = RxnString(null);

  String? get currentBirthday =>
      AgeZodiacSignUtil.formatBirthdayFromString(_currentBirthday.value);

  // 当前昵称
  final RxnString _currentNickname = RxnString(null);

  String? get currentNickname => _currentNickname.value;

  // 当前自定义键盘亲密度
  final RxInt _currentCustomIntimacy = 30.obs;

  int get currentCustomIntimacy => _currentCustomIntimacy.value;

  // 当前定制亲密度是否有变化
  final RxBool _customIntimacyChanged = false.obs;

  bool get customIntimacyChanged => _customIntimacyChanged.value;

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

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

  // 当前定制人设列表
  final RxList<CharacterInfo> _currentCustomKeyboardCharacterList = RxList();

  RxList<CharacterInfo> get currentCustomKeyboardCharacterList =>
      _currentCustomKeyboardCharacterList;

  ProfileEditController(this.configRepository, this.keyboardRepository);

  @override
  void onInit() {
    super.onInit();
    final KeyboardInfo? keyboardInfo = Get.arguments?["keyboardInfo"];
    if (keyboardInfo != null) {
      mode = ProfileEditMode.edit;
      _currentCustomKeyboardInfo.value = keyboardInfo;
      _currentNickname.value = keyboardInfo.name;
      _currentGender.value = keyboardInfo.gender;
      _currentCustomIntimacy.value = keyboardInfo.intimacy ?? 30;
      _currentBirthday.value = keyboardInfo.birthday;
      _avatarUrl.value = keyboardInfo.imageUrl ?? "";
      getKeyboardCharacterList(keyboardId: keyboardInfo.id!);
    } else {
      mode = ProfileEditMode.add;
      _currentGender.value = null;
      _currentCustomIntimacy.value = 30;
      _avatarUrl.value = "";
    }

    ever<DefaultAvatarInfo?>(currentDefaultAvatarInfo, (info) {
      updateAvatarListsAndSelectFirst(info);
    });
  }

  @override
  void onReady() {
    super.onReady();
    updateAvatarListsAndSelectFirst(currentDefaultAvatarInfo.value);
  }

  void updateAvatarListsAndSelectFirst(DefaultAvatarInfo? info) {
    _boyAvatars.assignAll(info?.maleAvatars ?? []);
    _girlAvatars.assignAll(info?.femaleAvatars ?? []);
    if (_currentGender.value == 1 && _boyAvatars.isNotEmpty) {
      _avatarUrl.value = _boyAvatars[0];
    } else if (_girlAvatars.isNotEmpty) {
      _avatarUrl.value = _girlAvatars[0];
    }
  }

  clickSaveButton() async {
    AtmobLog.d(tag, 'clickSaveButton');
    if (!_validateForm()) return;

    AtmobLog.d(tag, 'generateKeyboard');

    try {
      LoadingDialog.show(isEditMode ? "更新键盘数据中" : "生成键盘中");
      if (isEditMode) {
        await _updateKeyboard();
        ToastUtil.show("更新键盘成功");
      } else {
        await _generateKeyboard();
        ToastUtil.show("生成键盘成功");
      }
      Get.back(result: true);
    } catch (error) {
      _handleError(error);
    } finally {
      LoadingDialog.hide();
    }
  }

  void nextAvatar() {
    List<String> avatars =
        _currentGender.value == 1 ? _boyAvatars : _girlAvatars;
    if (avatars.isEmpty) return;
    int currentIndex = avatars.indexOf(_avatarUrl.value);
    _avatarUrl.value = avatars[(currentIndex + 1) % avatars.length];
    AtmobLog.d(tag, 'nextAvatar: ${_avatarUrl.value}');
  }

  // 更新亲密度
  void updateIntimacy(int intimacy) {
    _currentCustomIntimacy.value = intimacy;
  }

  clickBack() {
    AtmobLog.d(tag, 'clickBackButton');
    Get.back();
  }

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

  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) {
      _avatarUrl.value = _boyAvatars.first;
    } else if (_girlAvatars.isNotEmpty) {
      _avatarUrl.value = _girlAvatars.first;
    }
  }

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

  void clickRelationship() {
    AtmobLog.d(tag, "clickRelationship");
  }

  void clickGoKeyboardManage() async {
    var result = await KeyboardManagePage.start(
      customKeyboardInfo: _currentCustomKeyboardInfo.value,
    );
    if (result != null && result is List<CharacterInfo>) {
      AtmobLog.d(tag, 'clickGoKeyboardManage result: $result');
      _currentCustomKeyboardCharacterList.assignAll(result);
    }
  }

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

  AssetGenImage? get genderImage {
    if (_currentGender.value == 1)
      return Assets.images.iconCharacterCustomDetailMale;
    if (_currentGender.value == 2)
      return Assets.images.iconCharacterCustomDetailFemale;
    return null;
  }

  bool _validateForm() {
    if (_currentNickname.value?.isEmpty ?? true) {
      ToastUtil.show("请输入昵称");
      return false;
    }
    if (_currentGender.value == null) {
      ToastUtil.show("请选择性别");
      return false;
    }
    if (_currentBirthday.value == null) {
      ToastUtil.show("请选择生日");
      return false;
    }
    if (_avatarUrl.value.isEmpty) {
      ToastUtil.show("请选择头像");
      return false;
    }
    if (isEditMode && _currentCustomKeyboardInfo.value.id == null) {
      ToastUtil.show("请先选择键盘");
      return false;
    }
    return true;
  }

  Future<void> _updateKeyboard() async {
    await keyboardRepository.updateKeyboardInfo(
      keyboardId: _currentCustomKeyboardInfo.value.id!,
      name: _currentNickname.value,
      imageUrl: _avatarUrl.value,
      birthday: _currentBirthday.value,
      gender: _currentGender.value,
      intimacy: _currentCustomIntimacy.value,
    );
  }

  Future<void> _generateKeyboard() async {
    await keyboardRepository.getKeyboardGenerate(
      name: _currentNickname.value!,
      gender: _currentGender.value!,
      imageUrl: _avatarUrl.value,
      birthday: _currentBirthday.value!,
      intimacy: _currentCustomIntimacy.value,
    );
  }

  void _handleError(dynamic error) {
    if (error is ServerErrorException) {
      ErrorHandler.toastError(error,message: error.message);
      AtmobLog.d(tag, 'clickSaveButton error: ${error.message}');
    } else {

      AtmobLog.d(tag, 'clickSaveButton error1: $error');
    }
  }

  // 获取当前键盘人设列表
  void getKeyboardCharacterList({required String keyboardId}) {
    keyboardRepository.getKeyboardCharacterList(keyboardId: keyboardId).then((
      keyboardCharacterListResponse,
    ) {
      AtmobLog.i(
        tag,
        'keyboardCharacterListResponse: ${keyboardCharacterListResponse.characterInfos.toString()}',
      );
      _currentCustomKeyboardCharacterList.assignAll(
        keyboardCharacterListResponse.characterInfos,
      );
    });
  }
}
