import 'package:cpt_profile/modules/profile_edit/dialog/avatar_edit_dialog.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:domain/repository/profile_repository.dart';
import 'package:flutter/material.dart';
import 'package:plugin_basic/provider/user_config/user_config_service.dart';
import 'package:plugin_platform/engine/dialog/dialog_engine.dart';
import 'package:plugin_platform/engine/notify/notify_engine.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:plugin_platform/http/dio/dio_cancelable_mixin.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/util.dart';
import 'profile_edit_state.dart';
import 'package:plugin_platform/platform_export.dart';

part 'profile_edit_view_model.g.dart';

@riverpod
class ProfileEditViewModel extends _$ProfileEditViewModel with DioCancelableMixin {
  late final ProfileRepository profileRepository;

  @override
  ProfileEditState build() {
    profileRepository = ref.read(profileRepositoryProvider);

    final state = initState();

    registerCancellation();

    return state;
  }

  // 获取默认的头像
  void fetchDefaultAvatar() async {
    final result = await profileRepository.fetchDefaultAvatar(cancelToken: cancelToken);
    if (result.isSuccess) {
      state = state.copyWith(defaultAvatars: result.list);
    } else {
      Log.e(result.errorMsg ?? "UnKnow Error");
    }
  }

  /// 提交编辑用户信息
  void submitEdit() async {
    final FocusNode firstNameFocusNode = state.formData['first_name']!['focusNode'];
    final FocusNode lastNameFocusNode = state.formData['last_name']!['focusNode'];
    final FocusNode emailFocusNode = state.formData['email']!['focusNode'];

    firstNameFocusNode.unfocus();
    lastNameFocusNode.unfocus();
    emailFocusNode.unfocus();

    final TextEditingController firstNameController = state.formData['first_name']!['controller'];
    final TextEditingController lastNameController = state.formData['last_name']!['controller'];
    final TextEditingController emailController = state.formData['email']!['controller'];

    final firstName = firstNameController.text;
    final lastName = lastNameController.text;
    final email = emailController.text;

    Log.d('当前待提交的 firstName:$firstName lastName:$lastName email:$email');

    if (Utils.isEmpty(firstName)) {
      ToastEngine.show('First Name cannot be empty!');
      return;
    }

    if (Utils.isEmpty(lastName)) {
      ToastEngine.show('Last Name cannot be empty!');
      return;
    }

    if (Utils.isEmpty(email)) {
      ToastEngine.show('Email cannot be empty!');
      return;
    }

    if (Utils.isEmpty(state.avatarPath)) {
      ToastEngine.show('Please select an avatar as your profile picture');
      return;
    }

    //执行密码登录
    final result = await profileRepository.updateProfile(
      firstName: firstName,
      lastName: lastName,
      email: email,
      avatarPath: state.avatarPath,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      //提示成功
      NotifyEngine.showSuccess(S.current.successful);
      //刷新用户信息
      UserConfigService.getInstance().refreshUserInfo();
      //返回
      appRouter.maybePop();
    } else {
      ToastEngine.show(result.errorMsg ?? "UnKnow Error");
    }
  }

  //去编辑头像页面
  void showAvatarEditDialog(BuildContext context) {
    DialogEngine.show(
        widget: AvatarEditDialog(
      otherAction: (path) {
        state = state.copyWith(avatarPath: path);
      },
      photoAction: () {
        //选择相机相册
        _pickPhoto(context);
      },
    ));
  }

  //相机相册选择
  void _pickPhoto(BuildContext context) {
    ImagePickerUtils().show(complete: (path) {
      if (path.isNotEmpty) {
        state = state.copyWith(avatarPath: path[0]);
      }
    });
  }

  // 初始化
  ProfileEditState initState() {
    final String? avatarPath = UserConfigService.getState().user?.avatar;
    final initState = ProfileEditState(avatarPath: Utils.isEmpty(avatarPath) ? null : avatarPath);

    final String? firstName = UserConfigService.getState().user?.information?.firstName;
    final String? lastName = UserConfigService.getState().user?.information?.lastName;
    final String? email = UserConfigService.getState().user?.email;

    final TextEditingController firstNameController = initState.formData['first_name']!['controller'];
    firstNameController.text = firstName ?? "";

    final TextEditingController lastNameController = initState.formData['last_name']!['controller'];
    lastNameController.text = lastName ?? "";

    final TextEditingController emailController = initState.formData['email']!['controller'];
    emailController.text = email ?? "";

    return initState;
  }
}
