import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:vitalapp/architecture/storage/storage.dart';
import 'package:vitalapp/components/button.dart';
import 'package:vitalapp/pages/home/personal_center/controller.dart';
import 'package:vitalapp/rpc.dart';

class AvatarPage extends GetView<PersonalCenterController> {
  const AvatarPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(0, 50, 10, 40),
      child: Stack(
        alignment: Alignment.center,
        children: [
          Column(
            children: [
              GestureDetector(
                child: Obx(
                  () => _buildHeadImageToken(controller.state.headImageToken),
                ),
              ),
              // VButton(
              //   onTap: () {},
              //   child: const Text(
              //     '保存头像',
              //     style: TextStyle(fontSize: 18),
              //   ),
              // )
            ],
          ),
          Positioned(
            bottom: 78,
            child: VButton(
              onTap: () {
                _openGallery();
              },
              child: const Text(
                '选择头像',
                style: TextStyle(fontSize: 18),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _openGallery() async {
    XFile? image = await ImagePicker().pickImage(source: ImageSource.gallery);
    final url = await rpc.storage.upload(image!);
    controller.state.headImageToken = url;
    controller.updateUserInfo();
  }

  Widget _buildHeadImageToken(String? headImageToken) {
    if (headImageToken?.isNotEmpty ?? false) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(200),
        child: Image.network(
          headImageToken!,
          width: 400,
          height: 400,
          fit: BoxFit.cover,
        ),
      );
    }
    return ClipRRect(
      borderRadius: BorderRadius.circular(200),
      child: Image.asset(
        'assets/images/avatar.png',
        width: 400,
        height: 400,
        fit: BoxFit.cover,
      ),
    );
  }
}
