import 'dart:convert';
import 'package:flutter/cupertino.dart';
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/ui_kit/theme/socialchat_theme.dart';
import 'package:yumi/ui_kit/components/sc_page_list.dart';
import 'package:yumi/app/routes/sc_fluro_navigator.dart';
import 'package:yumi/shared/data_sources/sources/repositories/sc_store_repository_imp.dart';
import 'package:yumi/ui_kit/widgets/bag/props_bag_theme_detail_dialog.dart';
import 'package:yumi/ui_kit/widgets/countdown_timer.dart';
import 'package:yumi/modules/store/store_route.dart';
import 'package:provider/provider.dart';
import '../../../../app/constants/sc_room_msg_type.dart';
import '../../../../shared/tools/sc_loading_manager.dart';
import '../../../../shared/business_logic/models/res/sc_room_theme_list_res.dart';
import '../../../../services/audio/rtc_manager.dart';
import '../../../../services/audio/rtm_manager.dart';
import '../../../../ui_kit/components/sc_debounce_widget.dart';
import '../../../../ui_kit/components/dialog/dialog_base.dart';
import '../../../../ui_kit/components/sc_tts.dart';
import '../../../../ui_kit/widgets/room/room_msg_item.dart';

///背包-房间主题
class BagsThemePage extends SCPageList {
  @override
  _BagsThemePageState createState() => _BagsThemePageState();
}

class _BagsThemePageState
    extends SCPageListState<SCRoomThemeListRes, BagsThemePage> {
  SCRoomThemeListRes? selecteTheme;

  @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,
    );
    loadData(1);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Column(
        children: [
          Expanded(child: buildList(context)),
          selecteTheme != null ? SizedBox(height: 10.w) : Container(),
          selecteTheme != null
              ? Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(12.w),
                    topRight: Radius.circular(12.w),
                  ),
                  color: Color(0xff18F2B1).withOpacity(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(
                            selecteTheme?.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:
                                  (selecteTheme?.useTheme ?? false)
                                      ? Colors.white
                                      : SocialChatTheme.primaryLight,
                            ),
                            child: text(
                              (selecteTheme?.useTheme ?? false)
                                  ? SCAppLocalizations.of(context)!.inUse
                                  : SCAppLocalizations.of(context)!.use,
                              fontWeight: FontWeight.w600,
                              fontSize: 14.sp,
                              textColor:
                                  !(selecteTheme?.useTheme ?? false)
                                      ? Colors.white
                                      : Color(0xffB1B1B1),
                            ),
                          ),
                          onTap: () {
                            if (!(selecteTheme?.useTheme ?? false)) {
                              ///佩戴
                              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(selecteTheme!, 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(selecteTheme!, true);
                                    },
                                  );
                                },
                              );
                            }
                          },
                        ),
                      ],
                    ),
                    SizedBox(height: 10.w),
                  ],
                ),
              )
              : Container(),
        ],
      ),
    );
  }

  @override
  Widget buildItem(SCRoomThemeListRes res) {
    return GestureDetector(
      child: Container(
        decoration: BoxDecoration(
          color: Color(0xff18F2B1).withOpacity(0.1),
          border: Border.all(
            color:
                selecteTheme?.id == res.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.themeBack ?? "",
                  width: 55.w,
                  height: 55.w,
                  borderRadius: BorderRadius.all(Radius.circular(8.w)),
                ),
                SizedBox(height: 8.w),
              ],
            ),
            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,
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
      onTap: () {
        selecteTheme = res;
        setState(() {});
      },
    );
  }

  ///加载数据
  @override
  loadPage({
    required int page,
    required Function(List<SCRoomThemeListRes>) onSuccess,
    Function? onErr,
  }) async {
    try {
      var storeList = await SCStoreRepositoryImp().roomThemeBackpack();
      for (var v in storeList) {
        if (v.useTheme ?? false) {
          selecteTheme = v;
          continue;
        }
      }
      onSuccess(storeList);
    } catch (e) {
      if (onErr != null) {
        onErr();
      }
    }
  }

  void _use(SCRoomThemeListRes res, bool unload) {
    SCLoadingManager.show();
    SCStoreRepositoryImp()
        .themeSwitchUse(res.id ?? "", unload)
        .then((value) async {
          SCLoadingManager.hide();
          SmartDialog.dismiss(tag: "showPropsDetail");
          if (!unload) {
            SCTts.show(SCAppLocalizations.of(context)!.successfulWear);
            Provider.of<RealTimeCommunicationManager>(
              context!,
              listen: false,
            ).updateRoomBG(res);
          } else {
            Provider.of<RealTimeCommunicationManager>(
              context!,
              listen: false,
            ).updateRoomBG(SCRoomThemeListRes());
            selecteTheme = null;
            SCTts.show(SCAppLocalizations.of(context)!.successfullyUnloaded);
          }
          loadData(1);

          ///发送一条消息更新远端房间信息
          String? groupId =
              Provider.of<RealTimeCommunicationManager>(
                context,
                listen: false,
              ).currenRoom?.roomProfile?.roomProfile?.roomAccount;
          if (groupId != null) {
            Msg msg = Msg(
              groupId: groupId,
              msg: unload ? "" : jsonEncode(res.toJson()),
              type: SCRoomMsgType.roomBGUpdate,
            );
            Provider.of<RtmProvider>(
              context!,
              listen: false,
            ).dispatchMessage(msg, addLocal: false);
          }
        })
        .catchError((e) {
          SCLoadingManager.hide();
        });
  }

  void _showDetail(SCRoomThemeListRes res) {
    SmartDialog.show(
      tag: "showPropsDetail",
      alignment: Alignment.center,
      animationType: SmartAnimationType.fade,
      builder: (_) {
        return PropsBagThemeDetailDialog(res, () {
          loadData(1);
        });
      },
    );
  }
}
