import 'package:chat/controllers/user_controller.dart';
import 'package:chat/routes/user_routes.dart';
import 'package:chat/services/auth_service.dart';
import 'package:chat/views/user/widgets/link_action_item.dart';
import 'package:chat/widgets/custom_avatar.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class UserInfoPage extends StatefulWidget {
  const UserInfoPage({Key? key}) : super(key: key);

  @override
  State<UserInfoPage> createState() => _UserInfoPageState();
}

class _UserInfoPageState extends State<UserInfoPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('个人资料'),
      ),
      body: GetX<AuthService>(
        builder: (_) {
          return SafeArea(
            child: Column(
              children: [
                LinkActionItem(
                  title: '头像',
                  onTap: () async {
                    final result = await AssetPicker.pickAssets(
                      Get.context!,
                      pickerConfig: const AssetPickerConfig(
                        maxAssets: 1,
                        requestType: RequestType.image,
                      ),
                    );

                    if (result == null) {
                      return;
                    }

                    _cropImage((await result.first.file)!.path);
                  },
                  isLink: true,
                  trailing: CustomAvatar(
                    _.userInfo.value.avatar,
                    size: 52,
                  ),
                ),
                LinkActionItem(
                  title: '昵称',
                  trailing: Text(_.userInfo.value.nickname!),
                  isLink: true,
                  onTap: () {
                    Get.toNamed(
                      UserRoutes.infoNickname,
                      arguments: {
                        'nickname': _.userInfo.value.nickname,
                      },
                    );
                  },
                ),
                Expanded(child: Container()),
              ],
            ),
          );
        },
      ),
    );
  }

  Future<void> _cropImage(String imagePath) async {
    CroppedFile? croppedFile = await ImageCropper().cropImage(
      sourcePath: imagePath,
      maxHeight: 128,
      maxWidth: 128,
      compressQuality: 70,
      aspectRatio: const CropAspectRatio(
        ratioX: 1,
        ratioY: 1,
      ),
      compressFormat: ImageCompressFormat.png,
      uiSettings: [
        IOSUiSettings(
          title: '头像剪裁',
          doneButtonTitle: '完成',
          cancelButtonTitle: '取消',
        ),
        AndroidUiSettings(
          toolbarTitle: '头像剪裁',
        ),
      ],
    );
    if (croppedFile != null) {
      UserController.to.uploadAvatar(croppedFile.path);
    }
  }
}
