import 'package:chat/configs/app_colors.dart';
import 'package:chat/controllers/private_controller.dart';
import 'package:chat/models/im/search_user_model.dart';
import 'package:chat/providers/user_provider.dart';
import 'package:chat/routes/contact_routes.dart';
import 'package:chat/routes/user_routes.dart';
import 'package:chat/services/auth_service.dart';
import 'package:chat/services/tim/apply_service.dart';
import 'package:chat/services/tim/friend_service.dart';
import 'package:chat/utils/convert.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/friend_type.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_application.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_check_result.dart';

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

  @override
  State<ContactFriendRequestPage> createState() => _ImFriendRequestState();
}

class _ImFriendRequestState extends State<ContactFriendRequestPage> {
  List<SearchUserModel>? searchList;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('新的朋友'),
        bottom: _Search(
          onChanged: (String e) async {
            if (e.isEmpty) {
              setState(() {
                searchList = null;
              });
            } else {
              var result = await UserProvider.searchUser(e);

              setState(() {
                searchList = result;
              });
            }
          },
        ),
      ),
      body: GestureDetector(
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ListView.separated(
                shrinkWrap: true,
                physics: const ClampingScrollPhysics(),
                itemCount: searchList?.length ?? 0,
                itemBuilder: (context, index) {
                  var user = searchList![index];
                  return FutureBuilder<V2TimFriendCheckResult?>(
                    future: TimFriendService.to.check(user.userID),
                    builder: (context, snapshot) {
                      V2TimFriendCheckResult? result = snapshot.data;
                      return ListTile(
                        leading: CustomAvatar(user.avatar),
                        title: Text(user.nickname),
                        onTap: () {
                          if (result?.resultType == 3) {
                            PrivateController.to.setCurrentFriend(user.userID);
                            Get.toNamed(
                              ContactRoutes.friendProfile,
                            );
                          }
                          Get.toNamed(
                            ContactRoutes.friendRequestApply,
                            arguments: {
                              'userID': user.userID,
                            },
                          );
                        },
                        trailing: _buildTrailing(result),
                      );
                    },
                  );
                },
                separatorBuilder: (context, index) {
                  return const Divider(
                    height: 0,
                    indent: 72,
                  );
                },
              ),
              const Divider(height: 0),
              const Padding(
                padding: EdgeInsets.only(
                  left: 16,
                  top: 4,
                ),
                child: Text(
                  '好友申请',
                  style: TextStyle(
                    color: AppColors.unactive,
                  ),
                ),
              ),
              GetX<TimApplyService>(
                builder: (_) {
                  return ListView.separated(
                    shrinkWrap: true,
                    physics: const ClampingScrollPhysics(),
                    itemBuilder: (context, index) {
                      V2TimFriendApplication apply = _.applies[index]!;
                      return ListTile(
                        leading: CustomAvatar(apply.faceUrl),
                        title: Text(apply.nickname!),
                        subtitle: Text(apply.addWording ?? ''),
                        trailing: apply.type ==
                                FriendApplicationType
                                    .V2TIM_FRIEND_APPLICATION_COME_IN
                            ? InkWell(
                                onTap: () {
                                  TimApplyService.to.accept(apply.userID);
                                },
                                child: Container(
                                  padding: const EdgeInsets.symmetric(
                                    vertical: 4,
                                    horizontal: 12,
                                  ),
                                  decoration: BoxDecoration(
                                    color: AppColors.primary,
                                    borderRadius: BorderRadius.circular(16),
                                  ),
                                  child: const Text(
                                    '通过请求',
                                    style: TextStyle(
                                      color: AppColors.white,
                                      fontSize: 12,
                                    ),
                                  ),
                                ),
                              )
                            : const Text('已发送'),
                        onTap: () {
                          PrivateController.to.setCurrentFriend(apply.userID);
                          Get.toNamed(
                            ContactRoutes.friendProfile,
                          );
                        },
                      );
                    },
                    separatorBuilder: (context, index) {
                      return const Divider(
                        height: 0,
                      );
                    },
                    itemCount: _.applies.length,
                  );
                },
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTrailing(V2TimFriendCheckResult? result) {
    if (result == null) {
      return const Text('');
    }
    if (result.resultType == 0) {
      return Container(
        padding: const EdgeInsets.symmetric(
          vertical: 4,
          horizontal: 8,
        ),
        decoration: BoxDecoration(
          color: AppColors.primary,
          borderRadius: BorderRadius.circular(16),
        ),
        child: const Text(
          '添加好友',
          style: TextStyle(
            color: AppColors.white,
            fontSize: 12,
          ),
        ),
      );
    }
    if (result.resultType == 2) {
      return const Text(
        '已申请',
        style: TextStyle(
          color: AppColors.unactive,
        ),
      );
    }
    if (result.resultType == 3) {
      return const Text('已是好友');
    }
    return Text(result.resultType.toString());
  }
}

class _Search extends StatelessWidget implements PreferredSizeWidget {
  final Function(String e) onChanged;

  const _Search({
    Key? key,
    required this.onChanged,
  }) : super(key: key);

  @override
  Size get preferredSize => const Size.fromHeight(64);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          constraints: const BoxConstraints(
            maxHeight: 32,
          ),
          padding: const EdgeInsets.symmetric(horizontal: 16),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(16),
            child: TextField(
              keyboardType: TextInputType.phone,
              decoration: InputDecoration(
                hintText: '请输入对方的区块链地址',
                hintStyle: const TextStyle(
                  fontSize: 14,
                  color: AppColors.unactive,
                ),
                border: InputBorder.none,
                focusedBorder: InputBorder.none,
                fillColor: AppColors.unactive.withOpacity(0.1),
                filled: true,
                prefixIcon: const Icon(
                  Icons.search,
                  color: AppColors.unactive,
                  size: 18,
                ),
                contentPadding: const EdgeInsets.only(
                  bottom: 14,
                ),
              ),
              cursorColor: AppColors.primary,
              onChanged: (e) async {
                onChanged.call(e);
              },
            ),
          ),
        ),
        Container(
          padding: const EdgeInsets.only(
            top: 8,
            bottom: 16,
            left: 16,
            right: 16,
          ),
          child: InkWell(
            onTap: () {
              Get.toNamed(UserRoutes.qrCode);
            },
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  '我的地址: ' +
                      Convert.hideCenterStr(
                        AuthService.to.userInfo.value.address!,
                        start: 4,
                        end: 4,
                      ),
                  style: const TextStyle(
                    color: AppColors.unactive,
                  ),
                ),
                const SizedBox(width: 8),
                const Icon(
                  Icons.qr_code,
                  size: 18,
                  color: AppColors.unactive,
                ),
              ],
            ),
          ),
        ),
        const Divider(height: 0),
      ],
    );
  }
}
