import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_debouncer/flutter_debouncer.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:yumi/ui_kit/theme/socialchat_theme.dart';
import 'package:provider/provider.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/components/sc_tts.dart';
import 'package:yumi/app/constants/sc_room_msg_type.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/services/audio/rtc_manager.dart';
import 'package:yumi/services/audio/rtm_manager.dart';
import 'package:yumi/modules/store/store_route.dart';
import 'package:yumi/ui_kit/widgets/room/room_msg_item.dart';

import '../../../shared/business_logic/models/res/sc_room_theme_list_res.dart';

class PropsBagThemeDetailDialog extends StatefulWidget {
  SCRoomThemeListRes res;
  Function() refresh;

  PropsBagThemeDetailDialog(this.res, this.refresh);

  @override
  _PropsBagThemeDetailDialogState createState() =>
      _PropsBagThemeDetailDialogState();
}

class _PropsBagThemeDetailDialogState extends State<PropsBagThemeDetailDialog> {
  final debouncer = Debouncer();

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

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 280.w,
      width: 230.w,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(10.w)),
      ),
      child: Stack(
        children: [
          Column(
            children: [
              SizedBox(height: 20.w),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  text(
                    SCAppLocalizations.of(context)!.viewFrame,
                    fontSize: 16.w,
                    textColor: Colors.black,
                    fontWeight: FontWeight.bold,
                  ),
                ],
              ),
              SizedBox(height: 20.w),
              netImage(
                url: widget.res?.themeBack ?? "",
                width: 110.w,
                height: 110.w,
                borderRadius: BorderRadius.all(Radius.circular(8.w)),
              ),
              SizedBox(height: 20.w),
              GestureDetector(
                child: Container(
                  alignment: Alignment.center,
                  width: 130.w,
                  padding: EdgeInsets.symmetric(vertical: 10.w),
                  decoration: BoxDecoration(
                    color: SocialChatTheme.primaryLight,
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: text(
                    (widget.res.expireTime ?? 0) > 0
                        ? ((widget.res.expireTime ?? 0) <
                                DateTime.now().millisecondsSinceEpoch
                            ? SCAppLocalizations.of(context)!.renewal
                            : widget.res.useTheme ?? false
                            ? SCAppLocalizations.of(context)!.unUse
                            : SCAppLocalizations.of(context)!.use)
                        : ((widget.res.useTheme ?? false)
                            ? SCAppLocalizations.of(context)!.unUse
                            : SCAppLocalizations.of(context)!.use),
                    fontSize: 16.sp,
                    textColor: Colors.white,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                onTap: () {
                  debouncer.debounce(
                    duration: Duration(milliseconds: 350),
                    onDebounce: () {
                      if ((widget.res.expireTime ?? 0) <= 0) {
                      } else {
                        if ((widget.res.expireTime ?? 0) <
                            DateTime.now().millisecondsSinceEpoch) {
                          ///过期 续费操作
                          SCNavigatorUtils.push(
                            context,
                            StoreRoute.list,
                            replace: false,
                          );
                          return;
                        }
                      }

                      if (widget.res.useTheme ?? false) {
                        ///卸下
                        _use(widget.res, true);
                      } else {
                        ///佩戴
                        _use(widget.res, false);
                      }
                    },
                  );
                },
              ),
            ],
          ),
          Positioned(
            right: 20.w,
            top: 18.w,
            child: GestureDetector(
              child: Icon(Icons.close, size: 20.w),
              onTap: () {
                SmartDialog.dismiss(tag: "showPropsDetail");
              },
            ),
          ),
        ],
      ),
    );
  }

  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());
            SCTts.show(SCAppLocalizations.of(context)!.successfullyUnloaded);
          }

          ///发送一条消息更新远端房间信息
          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);
          }
          widget.refresh();
        })
        .catchError((e) {
          SCLoadingManager.hide();
        });
  }
}
