import 'package:flutter/material.dart';
import 'package:injectable/injectable.dart';
import 'package:keyboard/data/bean/keyboard_info.dart';
import 'package:keyboard/data/repository/keyboard_repository.dart';
import 'package:keyboard/main.dart';
import 'package:keyboard/module/main/main_page.dart';
import 'package:keyboard/module/new_user/result/new_user_result_page.dart';
import 'package:keyboard/module/new_user/step/birthday/step_birthday_logic.dart';
import 'package:keyboard/module/new_user/step/gender/step_gender_logic.dart';
import 'package:keyboard/module/new_user/step/intimacy/step_intimacy_stages_logic.dart';
import 'package:keyboard/module/new_user/step/nickname/step_nickname_logic.dart';
import 'package:keyboard/module/new_user/step/partner/step_partner_logic.dart';
import 'package:keyboard/resource/string.gen.dart';
import 'package:keyboard/utils/atmob_log.dart';
import 'package:intl/intl.dart';
import '../../base/base_controller.dart';
import '../../data/api/response/keyboard_generate_response.dart';
import '../../data/bean/default_avatar_info.dart';
import '../../data/consts/constants.dart';
import '../../data/repository/account_repository.dart';
import 'package:get/get.dart';

import '../../dialog/keyboard_generating_dialog.dart';
import '../../utils/error_handler.dart';
import '../../utils/http_handler.dart';
import '../../utils/toast_util.dart';

enum NewUserStepType {
  stepGenDer(0),
  stepBirthday(1),
  stepNickname(2),
  stepIntimacyStages(3),
  stepPartner(4);

  final int value;

  const NewUserStepType(this.value);
}

@injectable
class NewUserController extends BaseController
    with
        StepGenDerLogic,
        StepBirthdayLogic,
        StepNicknameLogic,
        StepIntimacyStagesLogic,
        StepPartnerLogic {
  final AccountRepository accountRepository;
  final KeyboardRepository keyboardRepository;

  NewUserController(this.accountRepository, this.keyboardRepository);

  final RxInt _currentStep = 1.obs;

  int get currentStep => _currentStep.value;

  final RxInt _totalSteps = 5.obs;

  int get totalSteps => _totalSteps.value;

  final PageController pageController = PageController();

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

  @override
  void onInit() {
    super.onInit();

    updateAvatarListsAndSelectFirst(currentDefaultAvatarInfo.value);

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

  void clickBack() {
    if (currentStep > 1) {
      pageController.previousPage(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
      _currentStep.value--;
    } else {
      Get.back();
    }
  }

  Future<void> clickNextButton() async {
    if (!isCurrentStepValid) {
      ToastUtil.show(currentStepValidationError ?? "请完成当前步骤");
      return;
    }

    if (currentStep == totalSteps) {
      _generateKeyboard();
    } else {

     await _settingUseInfo();

    }
  }

  void clickUseGeneralMode() {

    MainPage.start();
  }

  void clickSkip() {
    MainPage.start();
  }

  /// 当前步骤是否完成验证
  bool get isCurrentStepValid {
    switch (currentStep) {
      case 1: // 性别
        return currentGender != null;
      case 2: // 生日
        return currentBirthday != null;
      case 3: // 昵称
        return nickname.trim().isNotEmpty;
      case 4: // 亲密阶段
        return currentIntimacyMedian > 0;
      case 5: // 伴侣信息
        return partnerName.value.trim().isNotEmpty &&
            currentPartnerBirthday != null &&
            partnerAvatarUrl.isNotEmpty &&
            partnerGender != null;
      default:
        return false;
    }
  }

  /// 获取当前步骤未完成提示
  String? get currentStepValidationError {
    switch (currentStep) {
      case 1:
        return currentGender == null ? "请选择性别" : null;
      case 2:
        return currentBirthday == null ? "请选择生日" : null;
      case 3:
        if (nickname.trim().isEmpty) return "请输入昵称";
        if (nickname.value.length > 5) return "昵称最多5个字";

        if (nickname.contains(' ')) return "昵称不能包含空格";
        return null;
      case 4:
        return currentIntimacyMedian == 0 ? "请选择亲密阶段" : null;
      case 5:
        if (partnerName.value.isEmpty) return "请填写TA姓名";
        if (partnerGender == null) return "请选择TA性别";
        if (currentPartnerBirthday == null) return "请填写TA生日";
        if (partnerAvatarUrl.isEmpty) return "请选择TA头像";
        return null;
      default:
        return null;
    }
  }

  Future<void> _settingUseInfo() async {
    try {
      await  accountRepository.setUserInfo(
        name: nickname.value,
        birthday:
        currentBirthday != null
            ? DateFormat('yyyy-MM-dd').format(currentBirthday!)
            : null,
        gender: currentGender,
        imageUrl: null,
      );
      pageController.nextPage(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeIn,
      );
      _currentStep.value++;
      accountRepository.refreshUserInfo();
    } catch (error) {
      if (error is ServerErrorException) {
        ToastUtil.show(error.message);
      } else {
        ErrorHandler.toastError(error);
      }
    }
  }

  Future<void> _generateKeyboard() async {
    KeyboardGeneratingDialog.show(text: StringName.newUserKeyboardGenerating);
    try {
      KeyboardGenerateResponse keyboardGenerateResponse =
          await keyboardRepository.getKeyboardGenerate(
            name: partnerName.value,
            gender: partnerGender!,
            imageUrl: partnerAvatarUrl,
            birthday: DateFormat('yyyy-MM-dd').format(currentPartnerBirthday!),
            intimacy: currentIntimacyMedian,
          );
      if (keyboardGenerateResponse.keyboardInfo == null) {
        ToastUtil.show("生成失败");
        KeyboardGeneratingDialog.hide();
        return;
      }
      _keyboardInfo.value = keyboardGenerateResponse.keyboardInfo!;

      keyboardRepository.refreshData();
      Future.delayed(const Duration(seconds: 3), () {
        KeyboardGeneratingDialog.hide();
        NewUserResultPage.start(
          newUserKeyboardInfo: _keyboardInfo.value,
        );
      });
    } catch (error) {
      KeyboardGeneratingDialog.hide();
      if (error is ServerErrorException) {
        ToastUtil.show(error.message);
        AtmobLog.d(tag, '_generateKeyboard error: ${error.message}');
      } else {
        AtmobLog.d(tag, '_generateKeyboard error: $error');
      }
    }
  }
}
