import 'package:flutter/material.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_compontent.dart';
import 'package:yumi/ui_kit/components/text/sc_text.dart';
import 'package:yumi/shared/data_sources/sources/local/user_manager.dart';
import 'package:provider/provider.dart';
import 'package:yumi/ui_kit/components/dialog/dialog_base.dart';
import 'package:yumi/ui_kit/components/sc_page_list.dart';
import 'package:yumi/ui_kit/components/sc_tts.dart';
import 'package:yumi/app/routes/sc_fluro_navigator.dart';
import 'package:yumi/shared/tools/sc_loading_manager.dart';
import 'package:yumi/shared/data_sources/sources/repositories/sc_store_repository_imp.dart';
import 'package:yumi/shared/business_logic/models/res/bags_list_res.dart';
import 'package:yumi/shared/business_logic/models/res/login_res.dart';
import 'package:yumi/services/auth/user_profile_manager.dart';
import 'package:yumi/ui_kit/widgets/bag/props_bag_chatbox_detail_dialog.dart';
import 'package:yumi/ui_kit/widgets/countdown_timer.dart';
import 'package:yumi/modules/store/store_route.dart';
import 'package:yumi/ui_kit/widgets/store/store_bag_page_helpers.dart';

import '../../../../shared/data_sources/models/enum/sc_props_type.dart';
import '../../../../ui_kit/components/sc_debounce_widget.dart';
import '../../../../ui_kit/theme/socialchat_theme.dart';

///背包-气泡框
class BagsChatboxPage extends SCPageList {
  @override
  _BagsChatboxPageState createState() => _BagsChatboxPageState();
}

class _BagsChatboxPageState
    extends SCPageListState<BagsListRes, BagsChatboxPage> {
  ///自己当前佩戴的气泡框
  PropsResources? myChatbox;
  BagsListRes? selecteChatbox;

  @override
  void initState() {
    super.initState();
    enablePullUp = false;
    isGridView = true;
    gridViewCount = 3;
    padding = EdgeInsets.symmetric(horizontal: 6.w);
    backgroundColor = Colors.transparent;
    gridDelegate = SliverGridDelegateWithFixedCrossAxisCount(
      crossAxisCount: gridViewCount,
      mainAxisSpacing: 12.w,
      crossAxisSpacing: 12.w,
      childAspectRatio: 0.88,
    );
    myChatbox = AccountStorage().getChatbox();
    loadData(1);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Column(
        children: [
          Expanded(
            child:
                items.isEmpty && isLoading
                    ? const SCBagGridSkeleton()
                    : buildList(context),
          ),
          selecteChatbox != null ? SizedBox(height: 10.w) : Container(),
          selecteChatbox != null
              ? Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(12.w),
                    topRight: Radius.circular(12.w),
                  ),
                  color: const Color(0xff18F2B1).withValues(alpha: 0.1),
                ),
                child: Column(
                  children: [
                    SizedBox(height: 5.w),
                    Row(
                      spacing: 5.w,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        text(
                          "${SCAppLocalizations.of(context)!.expirationTime}:",
                          textColor: Colors.white,
                          fontSize: 12.sp,
                        ),
                        CountdownTimer(
                          fontSize: 11.sp,
                          color: SocialChatTheme.primaryLight,
                          expiryDate: DateTime.fromMillisecondsSinceEpoch(
                            selecteChatbox?.expireTime ?? 0,
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 10.w),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        SCDebounceWidget(
                          child: Container(
                            alignment: Alignment.center,
                            width: 120.w,
                            height: 35.w,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(12.w),
                              color: SocialChatTheme.primaryLight,
                            ),
                            child: text(
                              SCAppLocalizations.of(context)!.renewal,
                              fontWeight: FontWeight.w600,
                              fontSize: 14.sp,
                              textColor: Colors.white,
                            ),
                          ),
                          onTap: () {
                            ///过期 续费操作
                            SCNavigatorUtils.push(
                              context,
                              StoreRoute.list,
                              replace: false,
                            );
                          },
                        ),
                        SizedBox(width: 10.w),
                        SCDebounceWidget(
                          child: Container(
                            alignment: Alignment.center,
                            width: 120.w,
                            height: 35.w,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(12.w),
                              color:
                                  myChatbox?.id ==
                                          selecteChatbox?.propsResources?.id
                                      ? Colors.white
                                      : SocialChatTheme.primaryLight,
                            ),
                            child: text(
                              myChatbox?.id ==
                                      selecteChatbox?.propsResources?.id
                                  ? SCAppLocalizations.of(context)!.inUse
                                  : SCAppLocalizations.of(context)!.use,
                              fontWeight: FontWeight.w600,
                              fontSize: 14.sp,
                              textColor:
                                  myChatbox?.id !=
                                          selecteChatbox?.propsResources?.id
                                      ? Colors.white
                                      : Color(0xffB1B1B1),
                            ),
                          ),
                          onTap: () {
                            if (myChatbox?.id !=
                                selecteChatbox?.propsResources?.id) {
                              ///佩戴
                              SmartDialog.show(
                                tag: "showConfirmDialog",
                                alignment: Alignment.center,
                                debounce: true,
                                animationType: SmartAnimationType.fade,
                                builder: (_) {
                                  return MsgDialog(
                                    title: SCAppLocalizations.of(context)!.tips,
                                    msg:
                                        SCAppLocalizations.of(
                                          context,
                                        )!.confirmUseTips,
                                    btnText:
                                        SCAppLocalizations.of(context)!.confirm,
                                    onEnsure: () {
                                      _use(selecteChatbox!, false);
                                    },
                                  );
                                },
                              );
                            } else {
                              ///卸下
                              SmartDialog.show(
                                tag: "showConfirmDialog",
                                alignment: Alignment.center,
                                debounce: true,
                                animationType: SmartAnimationType.fade,
                                builder: (_) {
                                  return MsgDialog(
                                    title: SCAppLocalizations.of(context)!.tips,
                                    msg:
                                        SCAppLocalizations.of(
                                          context,
                                        )!.confirmUnUseTips,
                                    btnText:
                                        SCAppLocalizations.of(context)!.confirm,
                                    onEnsure: () {
                                      _use(selecteChatbox!, true);
                                    },
                                  );
                                },
                              );
                            }
                          },
                        ),
                      ],
                    ),
                    SizedBox(height: 10.w),
                  ],
                ),
              )
              : Container(),
        ],
      ),
    );
  }

  @override
  Widget buildItem(BagsListRes res) {
    return GestureDetector(
      child: Container(
        decoration: BoxDecoration(
          color: const Color(0xff18F2B1).withValues(alpha: 0.1),
          border: Border.all(
            color:
                selecteChatbox?.propsResources?.id == res.propsResources?.id
                    ? SocialChatTheme.primaryLight
                    : Colors.transparent,
            width: 1.w,
          ),
          borderRadius: BorderRadius.all(Radius.circular(8.w)),
        ),
        child: Stack(
          alignment: Alignment.center,
          children: [
            Column(
              children: [
                SizedBox(height: 25.w),
                netImage(
                  url: res.propsResources?.cover ?? "",
                  height: 35.w,
                  fit: BoxFit.contain,
                ),
                SizedBox(height: 8.w),
                buildStoreBagItemTitle(
                  res.propsResources?.name ?? "",
                  textColor: Colors.black,
                  fontSize: 12.sp,
                ),
              ],
            ),
            PositionedDirectional(
              top: 0,
              start: 0,
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 5.w),
                decoration: BoxDecoration(
                  color: SocialChatTheme.primaryLight,
                  borderRadius: BorderRadiusDirectional.only(
                    topStart: Radius.circular(6.w),
                    topEnd: Radius.circular(12.w),
                    bottomEnd: Radius.circular(12.w),
                  ),
                ),
                child: Row(
                  children: [
                    CountdownTimer(
                      fontSize: 9.sp,
                      color: Colors.white,
                      expiryDate: DateTime.fromMillisecondsSinceEpoch(
                        res.expireTime ?? 0,
                      ),
                    ),
                    SizedBox(width: 3.w),
                    Image.asset(
                      "sc_images/store/sc_icon_bag_clock.png",
                      width: 22.w,
                      height: 22.w,
                    ),
                  ],
                ),
              ),
            ),
            PositionedDirectional(
              bottom: 5.w,
              end: 5.w,
              child: GestureDetector(
                onTap: () {
                  selecteChatbox = res;
                  setState(() {});
                  _showDetail(res);
                },
                behavior: HitTestBehavior.opaque,
                child: Container(
                  padding: EdgeInsets.all(5.w),
                  child: Image.asset(
                    "sc_images/store/sc_icon_shop_item_search.png",
                    width: 18.w,
                    height: 18.w,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
      onTap: () {
        selecteChatbox = res;
        setState(() {});
      },
    );
  }

  ///加载数据
  @override
  loadPage({
    required int page,
    required Function(List<BagsListRes>) onSuccess,
    Function? onErr,
  }) async {
    try {
      var storeList = await SCStoreRepositoryImp().storeBackpack(
        AccountStorage().getCurrentUser()?.userProfile?.id ?? "",
        SCPropsType.CHAT_BUBBLE.name,
      );
      for (var v in storeList) {
        if (v.propsResources?.id == myChatbox?.id) {
          selecteChatbox = v;
          continue;
        }
      }
      onSuccess(storeList);
    } catch (e) {
      if (onErr != null) {
        onErr();
      }
    }
  }

  void _showDetail(BagsListRes res) {
    SmartDialog.show(
      tag: "showPropsDetail",
      alignment: Alignment.center,
      animationType: SmartAnimationType.fade,
      builder: (_) {
        return PropsBagChatboxDetailDialog(res);
      },
      onDismiss: () {
        myChatbox = AccountStorage().getChatbox();
        setState(() {});
      },
    );
  }

  void _use(BagsListRes res, bool unload) {
    SCLoadingManager.show(context: context);
    SCStoreRepositoryImp()
        .switchPropsUse(
          SCPropsType.CHAT_BUBBLE.name,
          res.propsResources?.id ?? "",
          unload,
        )
        .then((value) async {
          setState(() {});
          if (!unload) {
            myChatbox = res.propsResources;
            SCTts.show(SCAppLocalizations.of(context)!.successfulWear);
          } else {
            myChatbox = null;
            SCTts.show(SCAppLocalizations.of(context)!.successfullyUnloaded);
          }
          Provider.of<SocialChatUserProfileManager>(
            context,
            listen: false,
          ).fetchUserProfileData(loadGuardCount: false);
          SCLoadingManager.hide();
        })
        .catchError((e) {
          SCLoadingManager.hide();
        });
  }
}
