import 'package:chat/configs/app_colors.dart';
import 'package:chat/routes/conversation_routes.dart';
import 'package:chat/services/tim/conversation_service.dart';
import 'package:chat/services/tim/friend_service.dart';
import 'package:chat/services/tim/group_service.dart';
import 'package:chat/views/home/widgets/friend_selector.dart';
import 'package:chat/widgets/custom_avatar.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tencent_im_sdk_plugin/enum/group_type.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info.dart';

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

  @override
  State<ContactGroupCreateUserPage> createState() =>
      _ContactGroupCreateUserPageState();
}

class _ContactGroupCreateUserPageState
    extends State<ContactGroupCreateUserPage> {
  final ScrollController _scrollController = ScrollController();

  late final String groupType;

  /// 选中的好友列表
  List<V2TimFriendInfo> _selectList =
      List<V2TimFriendInfo>.empty(growable: true);

  @override
  void initState() {
    super.initState();
    groupType = Get.arguments['groupType'];
    TimFriendService.to.fetchList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '发起群聊',
        ),
      ),
      body: SafeArea(
        top: false,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              color: Colors.white,
              height: 58,
              padding: const EdgeInsets.all(
                4,
              ),
              child: ListView.builder(
                controller: _scrollController,
                scrollDirection: Axis.horizontal,
                itemCount: _selectList.length,
                itemBuilder: (context, index) {
                  return Container(
                    width: 50,
                    height: 50,
                    padding: const EdgeInsets.all(4),
                    child: GestureDetector(
                      onTap: () {
                        setState(() {
                          _selectList.removeAt(index);
                        });
                      },
                      child: CustomAvatar(
                        _selectList[index].userProfile!.faceUrl,
                        size: 42,
                      ),
                    ),
                  );
                },
              ),
            ),
            const Divider(height: 0),
            Container(
              color: AppColors.unactive.withOpacity(0.1),
              alignment: Alignment.centerLeft,
              padding: const EdgeInsets.only(
                left: 16,
              ),
              height: 40,
              width: double.infinity,
              child: const Text(
                '选择群成员',
                style: TextStyle(
                  fontSize: 14,
                ),
              ),
            ),
            Expanded(
              child: FriendSelector(
                onChanged: onChanged,
              ),
            ),
            Container(
              padding: const EdgeInsets.only(
                right: 16,
                left: 16,
                top: 4,
              ),
              decoration: const BoxDecoration(
                color: Colors.white,
                border: Border(
                  top: BorderSide(
                    color: Colors.black12,
                    width: 0.4,
                  ),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '已选 ${_selectList.length}',
                    style: const TextStyle(
                      color: Colors.grey,
                    ),
                  ),
                  ElevatedButton(
                    onPressed:
                        _selectList.isNotEmpty && _selectList.length < 200
                            ? _createGroup
                            : null,
                    child: const Text(
                      '完成',
                    ),
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 好友选择，添加到选择列表
  Future onChanged(e) async {
    setState(() {
      _selectList = e;

      Future.delayed(const Duration(milliseconds: 200), () {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 200),
          curve: Curves.bounceIn,
        );
      });
    });
  }

  /// 创建群聊
  Future<void> _createGroup() async {
    String groupName = '创建的群聊';
    var result = await TimGroupService.to.create(
      groupName,
      _selectList,
      groupType: GroupType.Public,
    );

    if (result != null) {
      Get.offNamed(
        ConversationRoutes.index,
        arguments: {
          'conversation': await TimConversationService.to.getById(
            'group_' + result,
          ),
        },
      );
    }
  }
}
