import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:injectable/injectable.dart';
import 'package:keyboard/base/base_controller.dart';
import 'package:keyboard/data/bean/custom_config_info.dart';
import 'package:keyboard/data/repository/config_repository.dart';
import 'package:keyboard/module/character_custom/detail/character_custom_detail_page.dart';
import 'package:keyboard/module/character_custom/list/character_custom_list_page.dart';
import 'package:keyboard/resource/string.gen.dart';
import 'package:keyboard/utils/atmob_log.dart';

import '../../dialog/custom_label_dialog.dart';
import '../../utils/toast_util.dart';

enum StepType {
  home(0),
  hobbies(1),
  characters(2),
  inputName(3);

  final int value;

  const StepType(this.value);
}

@injectable
class CharacterCustomController extends BaseController {
  final String tag = 'CharacterCustomController';

  final ConfigRepository configRepository;

  CustomConfigInfo? get currentCharacterCustomConfig =>
      configRepository.characterCustomConfig.value;

  final RxList<Hobbies> hobbiesLabelsList = <Hobbies>[].obs;

  final RxList<Hobbies> hobbiesSelectLabels = <Hobbies>[].obs;

  final RxList<CharactersList> characterLabelsList = <CharactersList>[].obs;

  final RxList<CharactersList> characterSelectLabels = <CharactersList>[].obs;

  final Rx<StepType> currentStep = StepType.home.obs;

  final RxString currentNameValue = "".obs;

  CharacterCustomController(this.configRepository);

  // 是否从定制历史跳过来的
  final RxBool isSkipFromHistory = false.obs;

  @override
  void onInit() {
    super.onInit();
    initData();
    AtmobLog.d(tag, "首次加载数据，触发 refreshCharacterCustomConfig()");
  }

  //  初始化数据
  void initData() {
    AtmobLog.d(tag, "initData");
    hobbiesLabelsList.value = currentCharacterCustomConfig?.hobbies ?? [];
    characterLabelsList.value = currentCharacterCustomConfig?.characters ?? [];
  }

  // 自定义兴趣爱好
  void clickHobbiesCustom() {
    AtmobLog.d(tag, "clickHobbiesCustom");
    CustomLabelDialog.show(
      maxLength: currentCharacterCustomConfig?.maxHobbyWords ?? 5,
      hintText: StringName.customLabelHobbiesHint,
      clickCallback: (value) {
        final isExist = hobbiesLabelsList.map((e) => e.name).contains(value);
        if (isExist) {
          ToastUtil.show("添加失败，标签 $value 已存在");
          return;
        }
        final newHobby = Hobbies(name: value);
        hobbiesLabelsList.add(newHobby);
        ToastUtil.show("添加成功，标签 $value");
        // 如果当前已选未超限，自动选中
        if (hobbiesSelectLabels.length <
            (currentCharacterCustomConfig?.maxHobbyNum ?? 3)) {
          hobbiesSelectLabels.add(newHobby);
        } else {
          ToastUtil.show(
            "最多选择${currentCharacterCustomConfig?.maxHobbyNum ?? 3}个爱好",
          );
        }
      },
    );
  }

  // 自定义兴趣爱好
  void clickCharacterCustom() {
    AtmobLog.d(tag, "clickCharacterCustom");
    CustomLabelDialog.show(
      maxLength: currentCharacterCustomConfig?.maxCharacterWords ?? 5,
      hintText: StringName.customLabelCharacterHint,
      clickCallback: (value) {
        var isExist = characterLabelsList
            .map((e) => e.name)
            .contains(value);
        if (isExist) {
          ToastUtil.show("添加失败，标签 $value 已存在");
          return;
        }
        characterLabelsList.add(CharactersList(name: value));
        ToastUtil.show("添加成功，标签 $value");
        if (characterSelectLabels.length <
            (currentCharacterCustomConfig?.maxCharacterNum ?? 3)) {

          characterSelectLabels.add(CharactersList(name: value));
        } else {
          ToastUtil.show(
            "最多选择${currentCharacterCustomConfig?.maxCharacterNum ?? 3}个特质",
          );
        }
      },
    );
  }

  /// 返回上一页
  void clickBack() {
    AtmobLog.d(tag, "clickBack");
    if (currentStep.value == StepType.hobbies) {
      currentStep.value = StepType.home;
    } else if (currentStep.value == StepType.characters) {
      currentStep.value = StepType.hobbies;
    } else if (currentStep.value == StepType.inputName) {
      currentStep.value = StepType.characters;
    } else {
      if (isSkipFromHistory.value) {
        // 跳到定制历史
        clickHistory();
        isSkipFromHistory.value = false;
        return;
      }
      Get.back();
    }
  }

  // 爱好页的下一步
  void clickHobbiesNext() {
    int min = currentCharacterCustomConfig?.minHobbyNum ?? 1;
    int max = currentCharacterCustomConfig?.maxHobbyNum ?? 3;

    if (hobbiesSelectLabels.isEmpty) {
      ToastUtil.show("请选择爱好");
      return;
    }
    if (hobbiesSelectLabels.length < min) {
      ToastUtil.show("至少选择$min个爱好");
      return;
    }
    if (hobbiesSelectLabels.length > max) {
      ToastUtil.show("最多选择$max个爱好");
      return;
    }
    clickNextButton(StepType.characters);
  }

  // 性格页的下一步
  void clickCharacterNext() {
    int min = currentCharacterCustomConfig?.minCharacterNum ?? 1;
    int max = currentCharacterCustomConfig?.maxCharacterNum ?? 3;

    if (characterSelectLabels.isEmpty) {
      ToastUtil.show("请选择特质");
      return;
    }
    if (characterSelectLabels.length < min) {
      ToastUtil.show("至少选择$min个特质");
      return;
    }
    if (characterSelectLabels.length > max) {
      ToastUtil.show("最多选择$max个特质");
      return;
    }
    clickNextButton(StepType.inputName);
  }

  // 名字页的下一步
  Future<void> clickInputNameNext() async {
    if (currentNameValue.value.isEmpty) {
      ToastUtil.show("请输入名字");
      return;
    }
    if (currentNameValue.value.length > 5) {
      ToastUtil.show("最多5个字哦~");
      return;
    }

 await CharacterCustomDetailPage.start(
      hobbiesSelectLabels: hobbiesSelectLabels,
      characterSelectLabels: characterSelectLabels,
      characterCustomName: currentNameValue.value,
    );
    if (isSkipFromHistory.value) {
    //  跳到定制历史
      clickHistory();
      isSkipFromHistory.value = false;
    }
  }

  // 处理下一步
  void clickNextButton(StepType stepType) {
    if (currentCharacterCustomConfig == null) {
      AtmobLog.e(tag, "clickStartCustom - 当前配置为空");
      return;
    }
    if (stepType == StepType.hobbies) {
      currentStep.value = StepType.hobbies;
    } else if (stepType == StepType.characters) {
      currentStep.value = StepType.characters;
    } else if (stepType == StepType.inputName) {
      currentStep.value = StepType.inputName;
    } else {
      currentStep.value = StepType.home;
    }
  }

  /// 选择爱好标签
  void selectHobby(Hobbies hobby) {
    handleSelection(
      name: hobby,
      selectedList: hobbiesSelectLabels,
      max: currentCharacterCustomConfig?.maxHobbyNum ?? 3,
      errorMessage: "最多选择${currentCharacterCustomConfig?.maxHobbyNum ?? 3}个爱好",
    );
  }

  /// 选择性格标签
  void selectCharacter(CharactersList name) {
    handleSelection(
      name: name,
      selectedList: characterSelectLabels,
      max: currentCharacterCustomConfig?.maxCharacterNum ?? 3,
      errorMessage:
          "最多选择${currentCharacterCustomConfig?.maxCharacterNum ?? 3}个特质",
    );
  }

  Future<void> clickHistory() async {
    AtmobLog.d(tag, "clickHistory");
    var result = await CharacterCustomListPage.start();
    if (result != null) {
      AtmobLog.d(tag, "clickHistory");
      currentStep.value = result;
      isSkipFromHistory.value = true;
    }
  }

  ///标签选择处理
  void handleSelection({
    required dynamic name,
    required RxList<dynamic> selectedList,
    required int max,
    required String errorMessage,
  }) {
    if (selectedList.contains(name)) {
      selectedList.remove(name);
    } else if (selectedList.length < max) {
      selectedList.add(name);
    } else {
      ToastUtil.show(errorMessage);
    }
  }

  ///清空数据
  void clearData() {
    AtmobLog.d(tag, "clearData");
    currentStep.value = StepType.home;
    hobbiesSelectLabels.clear();
    characterSelectLabels.clear();
    currentNameValue.value = "";
    CharacterCustomListPage.start();
  }
}
