import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:yumi/app_localizations.dart';
import 'package:yumi/ui_kit/components/sc_debounce_widget.dart';
import 'package:yumi/ui_kit/components/text/sc_text.dart';
import 'package:yumi/app/routes/sc_fluro_navigator.dart';
import 'package:provider/provider.dart';

import 'package:yumi/ui_kit/components/appbar/socialchat_appbar.dart';
import 'package:yumi/ui_kit/components/dialog/dialog_base.dart';
import 'package:yumi/ui_kit/components/sc_compontent.dart';
import 'package:yumi/ui_kit/components/socialchat_gradient_button.dart';
import 'package:yumi/ui_kit/components/sc_page_list.dart';
import 'package:yumi/ui_kit/components/sc_tts.dart';
import 'package:yumi/shared/tools/sc_loading_manager.dart';
import 'package:yumi/shared/data_sources/sources/local/user_manager.dart';
import 'package:yumi/shared/data_sources/sources/repositories/sc_user_repository_impl.dart';
import 'package:yumi/shared/business_logic/models/res/login_res.dart';
import 'package:yumi/shared/business_logic/models/res/message_friend_user_res.dart';
import 'package:yumi/services/general/sc_app_general_manager.dart';
import 'package:yumi/modules/index/main_route.dart';

class UserBlockedListPage extends SCPageList {
  @override
  _UserBlockedListPageState createState() => _UserBlockedListPageState();
}

class _UserBlockedListPageState
    extends SCPageListState<MessageFriendUserRes, UserBlockedListPage> {
  late TextEditingController _textEditingController;
  String? lastId;

  @override
  void initState() {
    super.initState();
    _textEditingController = TextEditingController();
    enablePullUp = true;
    backgroundColor = Colors.transparent;
    isShowDivider = true;
    isShowFooter = false;
    padding = EdgeInsets.symmetric(horizontal: 10.w);
    loadData(1);
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Image.asset(
          "sc_images/person/sc_icon_edit_userinfo_bg.png",
          width: ScreenUtil().screenWidth,
          height: ScreenUtil().screenHeight,
          fit: BoxFit.fill,
        ),
        Scaffold(
          backgroundColor: Colors.transparent,
          resizeToAvoidBottomInset: false,
          appBar: SocialChatStandardAppBar(
            title: SCAppLocalizations.of(context)!.userBlacklist,
            actions: [],
          ),
          body: SafeArea(
            top: false,
            child: Column(
              children: [
                Row(
                  children: <Widget>[
                    SizedBox(width: 10.w),
                    Expanded(
                      child: searchWidget(
                        hint: SCAppLocalizations.of(context)!.searchUserId,
                        controller: _textEditingController,
                        borderColor: Colors.black12,
                        textColor: Colors.grey,
                      ),
                    ),
                    socialchatGradientButton(
                      text: SCAppLocalizations.of(context)!.search,
                      radius: 25,
                      textSize: 14.sp,
                      textColor: Colors.grey,
                      gradient: LinearGradient(
                        colors: [Colors.transparent, Colors.transparent],
                        begin: Alignment.centerLeft,
                        end: Alignment.centerRight,
                      ),
                      onPress: () {
                        if (_textEditingController.text.isNotEmpty) {
                          _search();
                        }
                      },
                    ),
                    SizedBox(width: 10.w),
                  ],
                ),
                SizedBox(height: 8.w),
                Expanded(child: buildList(context)),
                SizedBox(height: 8.w),
              ],
            ),
          ),
        ),
      ],
    );
  }

  @override
  Widget buildItem(MessageFriendUserRes res) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 8.w),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.w),
        color: Color(0xff18F2B1).withOpacity(0.1),
      ),
      child: Row(
        children: [
          SizedBox(width: 10.w),
          SCDebounceWidget(child: head(url: res.userProfile?.userAvatar ?? "", width: 62.w), onTap: (){
            SCNavigatorUtils.push(
              context,
              "${SCMainRoute.person}?isMe=${AccountStorage().getCurrentUser()?.userProfile?.id == res.userProfile?.id}&tageId=${res.userProfile?.id}",
            );
          })
          ,
          SizedBox(width: 10.w),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    netImage(
                      url:
                      Provider.of<SCAppGeneralManager>(context, listen: false)
                          .findCountryByName(
                        res.userProfile?.countryName ?? "",
                      )
                          ?.nationalFlag ??
                          "",
                      borderRadius: BorderRadius.all(Radius.circular(3.w)),
                      width: 19.w,
                      height: 14.w,
                    ),
                    SizedBox(width: 3.w),
                    socialchatNickNameText(
                      maxWidth: 148.w,
                      textColor: Colors.white,
                      res.userProfile?.userNickname ?? "",
                      fontSize: 14.sp,
                      type:res.userProfile?.getVIP()?.name ?? "",
                      needScroll:
                      (res.userProfile?.userNickname?.characters.length ?? 0) >
                          10,
                    ),
                    SizedBox(width: 3.w),
                    Container(
                      width: (res.userProfile?.age??0)>999?58.w:48.w,
                      height: 24.w,
                      decoration: BoxDecoration(
                        image: DecorationImage(
                          image: AssetImage(
                            res.userProfile?.userSex == 0
                                ? "sc_images/login/sc_icon_sex_woman_bg.png"
                                : "sc_images/login/sc_icon_sex_man_bg.png",
                          ),
                        ),
                      ),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          xb(res.userProfile?.userSex),
                          text(
                            "${res.userProfile?.age}",
                            textColor: Colors.white,
                            fontSize: 15.sp,
                            fontWeight: FontWeight.w600,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 4.w),
                Row(
                  children: [
                    GestureDetector(
                      child: Container(
                        child: Row(
                          textDirection: TextDirection.ltr,
                          children: [
                            text(
                              "ID:${res.userProfile?.getID()}",
                              fontSize: 12.sp,
                              textColor: Colors.white,
                              fontWeight: FontWeight.bold,
                            ),
                            SizedBox(width: 5.w),
                            Image.asset(
                              "sc_images/room/sc_icon_user_card_copy_id.png",
                              width: 12.w,
                              height: 12.w,
                            ),
                            SizedBox(width: 8.w),
                          ],
                        ),
                      ),
                      onTap: () {
                        Clipboard.setData(
                          ClipboardData(text: res.userProfile?.getID() ?? ""),
                        );
                        SCTts.show(
                          SCAppLocalizations.of(context)!.copiedToClipboard,
                        );
                      },
                    ),
                    SizedBox(width: 8.w),
                    getWealthLevel(
                      res.userProfile?.wealthLevel ?? 0,
                      width: 58.w,
                      height: 30.w,
                    ),
                    SizedBox(width: 8.w),
                    getUserLevel(
                      res.userProfile?.charmLevel ?? 0,
                      width: 58.w,
                      height: 30.w,
                    ),
                  ],
                ),
              ],
            ),
          ),
          SCDebounceWidget(child: Image.asset(
            "sc_images/room/sc_icon_block_list_delete.png",
            height: 20.w,
          ), onTap: (){
            _delete(res.userProfile);
          })
          ,
          SizedBox(width: 15.w),
        ],
      ),
    );
  }

  void _search() {
    SCAccountRepository()
        .userBlacklistList(account: _textEditingController.text)
        .then((result) {
          items = result;
          loadComplete();
          SCLoadingManager.hide();
          setState(() {});
        })
        .catchError((e) {
      SCLoadingManager.hide();
          loadComplete();
          setState(() {});
        });
  }

  @override
  builderDivider() {
    return Divider(
      height: 8.w,
      color: Color(0xffF2F2F2),
      indent: 15.w,
      endIndent: 15.w,
    );
  }

  ///加载数据
  @override
  loadPage({
    required int page,
    required Function(List<MessageFriendUserRes>) onSuccess,
    Function? onErr,
  }) async {
    if (_textEditingController.text.isNotEmpty) {
      _search();
    } else {
      if (page == 1) {
        lastId = null;
      }
      try {
        var userList = await SCAccountRepository().userBlacklistList(
          lastId: lastId,
        );
        if (userList.isNotEmpty) {
          lastId = userList.last.id;
        }
        SCLoadingManager.hide();
        onSuccess(userList);
      } catch (e) {
        SCLoadingManager.hide();
        if (onErr != null) {
          onErr();
        }
      }
    }
  }

  void _delete(SocialChatUserProfile? userProfile) {
    SmartDialog.show(
      tag: "showConfirmDialog",
      alignment:
      Alignment.center,
      debounce: true,
      animationType:
      SmartAnimationType
          .fade,
      builder: (_) {
        return MsgDialog(
          title:
          SCAppLocalizations.of(
            context!,
          )!.tips,
          msg:SCAppLocalizations.of(
            context,
          )!.areYouSureToCancelBlacklist,
          btnText:
          SCAppLocalizations.of(
            context,
          )!.confirm,
          onEnsure: () {
            SCLoadingManager.show();
            SCAccountRepository()
                .deleteUserBlacklist(
              userProfile?.id??"",
            )
                .then((
                result,
                ) {
              SCTts.show(
                SCAppLocalizations.of(
                  context,
                )!.successfullyRemovedFromTheBlacklist,
              );
              loadData(1);
            })
                .catchError((
                e,
                ) {
              SCLoadingManager.hide();
            });
          },
        );
      },
    );
  }
}
