import 'dart:ui' as ui;

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/components/sc_debounce_widget.dart';
import 'package:yumi/ui_kit/components/text/sc_text.dart';
import 'package:yumi/shared/data_sources/sources/local/user_manager.dart';
import 'package:yumi/shared/data_sources/sources/repositories/sc_room_repository_imp.dart';
import 'package:yumi/ui_kit/widgets/room/room_msg_item.dart';
import 'package:provider/provider.dart';

import 'package:yumi/app_localizations.dart';
import 'package:yumi/services/audio/rtc_manager.dart';
import 'package:yumi/services/audio/rtm_manager.dart';
import 'package:yumi/ui_kit/theme/socialchat_theme.dart';
import 'package:yumi/app/constants/sc_room_msg_type.dart';
import 'package:yumi/app/constants/sc_screen.dart';
import 'package:yumi/app/routes/sc_fluro_navigator.dart';
import 'package:yumi/ui_kit/components/sc_tts.dart';

// 基础对话框
class MsgDialog extends Dialog {
  final String msg;
  String title = "";
  String? btnText;
  String? cancelText;
  late BuildContext context;
  final VoidCallback onEnsure;
  final VoidCallback? onCancel;
  bool isDark = false;
  bool isBtnBgFlip = false;
  bool leftConfirm = false;

  MsgDialog({
    Key? key,
    this.title = "",
    required this.msg,
    required this.onEnsure,
    this.btnText,
    this.cancelText,
    this.isDark = false,
    this.isBtnBgFlip = false,
    this.leftConfirm = false,
    this.onCancel,
  });

  @override
  Widget build(BuildContext context) {
    this.context = context;

    return Material(
      //创建透明层
      type: MaterialType.transparency, //透明类型
      child: Stack(
        children: <Widget>[
          GestureDetector(
            onTap: () {
              //空白区域点击对话框消失
              SmartDialog.dismiss(tag: "showConfirmDialog");
            },
          ),
          _buildContentView(context),
        ],
      ),
    );
  }

  Widget _buildContentView(BuildContext context) {
    return Center(
      //保证控件居中效果
      child: Container(
        constraints: BoxConstraints(maxHeight: 420.w),
        margin: EdgeInsets.symmetric(horizontal: 18.w),
        decoration: ShapeDecoration(
          color: isDark ? Color(0xff161616) : Color(0xff09372E),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(width(10))),
          ),
        ),
        child: _buildDialog(context),
      ),
    );
  }

  Widget _buildDialog(BuildContext context) {
    return Stack(
      children: [
        Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            SizedBox(height: 15.w),
            title.isNotEmpty
                ? Container(
                  alignment: Alignment.center,
                  child: text(
                    title,
                    fontSize: 16.sp,
                    lineHeight: 1.1,
                    letterSpacing: 0.1,
                    textColor: isDark ? Colors.black : Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                )
                : Container(),
            SizedBox(height: 15.w),
            Container(
              margin: EdgeInsets.symmetric(horizontal: 8.w),
              alignment: Alignment.center,
              child: text(
                msg,
                maxLines: 20,
                fontSize: 14.sp,
                lineHeight: 1.1,
                letterSpacing: 0.1,
                textColor: isDark ? Colors.black : Colors.white,
                textAlign: TextAlign.center,
              ),
            ),
            SizedBox(height: 10.w),
            Container(
              margin: EdgeInsets.symmetric(horizontal: 15.w, vertical: 8.w),
              height: height(38),
              alignment: Alignment.center,
              child: Row(
                textDirection:
                    leftConfirm ? TextDirection.rtl : TextDirection.ltr,
                children: <Widget>[
                  Expanded(
                    child: GestureDetector(
                      child: Container(
                        decoration:
                            isBtnBgFlip
                                ? BoxDecoration(
                                  borderRadius: BorderRadius.circular(33.w),
                                  gradient: LinearGradient(
                                    begin: Alignment.topCenter,
                                    end: Alignment.bottomCenter,
                                    colors: [
                                      isDark
                                          ? Color(0xff260054)
                                          : Color(0xff18F2B1),
                                      isDark
                                          ? Color(0xff6105B7)
                                          : Color(0xff18F2B1),
                                    ],
                                  ),
                                )
                                : BoxDecoration(
                                  borderRadius: BorderRadius.circular(12.w),
                                  color:
                                      isDark
                                          ? Colors.transparent
                                          : Colors.transparent,
                                  border: Border.all(
                                    color: Colors.white,
                                    width: 1.w,
                                  ),
                                ),
                        alignment: Alignment.center,
                        child: text(
                          cancelText ?? SCAppLocalizations.of(context)!.cancel,
                          fontSize: 14.sp,
                          textColor:
                              isDark
                                  ? Colors.grey
                                  : (isBtnBgFlip ? Colors.black : Colors.white),
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      onTap: () {
                        onCancel?.call();
                        SmartDialog.dismiss(tag: "showConfirmDialog");
                      },
                    ),
                  ),
                  SizedBox(width: 15.w),
                  Expanded(
                    child: GestureDetector(
                      child: Container(
                        decoration:
                            isBtnBgFlip
                                ? BoxDecoration(
                                  borderRadius: BorderRadius.circular(12.w),
                                  color:
                                      isDark
                                          ? Colors.transparent
                                          : Colors.white,
                                  border: Border.all(
                                    color: Color(0xffE6E6E6),
                                    width: 1.w,
                                  ),
                                )
                                : BoxDecoration(
                                  borderRadius: BorderRadius.circular(12.w),
                                  gradient: LinearGradient(
                                    begin: Alignment.bottomLeft,
                                    end: Alignment.topRight,
                                    colors: [
                                      isDark
                                          ? Color(0xff260054)
                                          : Color(0xff18F2B1),
                                      isDark
                                          ? Color(0xff6105B7)
                                          : Color(0xff18F2B1),
                                    ],
                                  ),
                                ),
                        alignment: Alignment.center,
                        child: text(
                          btnText ?? SCAppLocalizations.of(context)!.yes,
                          fontSize: 14.sp,
                          textColor: isBtnBgFlip ? Colors.grey : Colors.black,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      onTap: () {
                        onEnsureClick();
                      },
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(height: 15.w),
          ],
        ),
        PositionedDirectional(
          end: 10.w,
          top: 10.w,
          child: SCDebounceWidget(
            child: Image.asset(
              "sc_images/general/sc_icon_msg_tips_close.png",
              height: 20.w,
            ),
            onTap: (){
              SmartDialog.dismiss(tag: "showConfirmDialog");
            },
          ),
        ),
      ],
    );
  }

  /*确定按钮点击事件*/
  onEnsureClick() {
    onEnsure();
    SmartDialog.dismiss(tag: "showConfirmDialog");
  }
}

// ignore: must_be_immutable
class OpenRoomLoadingDialog extends Dialog {
  String text;
  Widget? centerContent;
  final GestureTapCallback? verifyCallback;
  final double? height;
  final double? width;

  OpenRoomLoadingDialog({
    Key? key,
    this.text = "",
    this.height,
    this.width,
    this.centerContent,
    this.verifyCallback,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Material(
      //创建透明层
      type: MaterialType.transparency, //透明类型
      child: Center(
        //保证控件居中效果
        child: Container(
          constraints: BoxConstraints(maxWidth: ScreenUtil().screenWidth * 0.4),
          decoration: ShapeDecoration(
            color: Colors.black.withOpacity(0.78),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(10.0)),
            ),
          ),
          padding: EdgeInsets.all(15.w),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Image.asset("sc_images/raw/loading.webp", width: 80.w),
              SizedBox(height: 12.w),
              Text(
                "正在进入聊天室......",
                style: TextStyle(fontSize: 12.sp, color: Colors.white),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class DialogLine extends StatefulWidget {
  @override
  _DialogLineState createState() => _DialogLineState();
}

class _DialogLineState extends State<DialogLine> with TickerProviderStateMixin {
  late AnimationController animationController1;
  late AnimationController animationController2;
  late AnimationController animationController3;

  @override
  void initState() {
    // TODO: implement initState
    animationController1 = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 350),
    );
    animationController3 = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 350),
    );
    animationController2 = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 350),
    );
    animationController1.forward();
    animationController1.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        animationController1.reverse();
        animationController2.forward();
      }
    });
    animationController2.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        animationController2.reverse();
        animationController3.forward();
      }
    });
    animationController3.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        animationController3.reverse();
        animationController1.forward();
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    animationController1.dispose();
    animationController2.dispose();
    animationController3.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        ScaleTransition(
          scale: Tween(begin: 0.5, end: 1.0).animate(animationController1),
          child: _container(),
        ),
        SizedBox(width: 6),
        ScaleTransition(
          scale: Tween(begin: 0.5, end: 1.0).animate(animationController2),
          child: _container(),
        ),
        SizedBox(width: 6),
        ScaleTransition(
          scale: Tween(begin: 0.5, end: 1.0).animate(animationController3),
          child: _container(),
        ),
      ],
    );
  }

  Container _container() {
    return Container(
      height: 28,
      width: 28,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        gradient: LinearGradient(
          begin: Alignment.bottomCenter,
          end: Alignment.topCenter,
          colors: [
            Colors.deepPurpleAccent,
            Colors.deepPurpleAccent.withOpacity(0.5),
          ],
        ),
      ),
    );
  }
}

class KickedOutOfRoomDialog extends StatefulWidget {
  final String roomId;
  final String userId;

  const KickedOutOfRoomDialog({
    super.key,
    required this.roomId,
    required this.userId,
  });

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

class _KickedOutOfRoomDialogState extends State<KickedOutOfRoomDialog> {
  int selectType = -1;

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

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 260.w,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(12.w)),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(height: 22.w),
          text(
            SCAppLocalizations.of(context)!.kickedOutOfRoom,
            fontSize: 16.sp,
            textColor: Colors.black,
            fontWeight: FontWeight.bold,
          ),
          SizedBox(height: 14.w),
          GestureDetector(
            child: _buildItem("5 minutes", selectType == 0),
            onTap: () {
              setState(() {
                selectType = 0;
              });
            },
          ),
          SizedBox(height: 14.w),
          GestureDetector(
            child: _buildItem("24 hours", selectType == 1),
            onTap: () {
              setState(() {
                selectType = 1;
              });
            },
          ),
          SizedBox(height: 14.w),
          GestureDetector(
            child: _buildItem("1 month", selectType == 2),
            onTap: () {
              setState(() {
                selectType = 2;
              });
            },
          ),
          SizedBox(height: 14.w),
          GestureDetector(
            child: _buildItem(
              SCAppLocalizations.of(context)!.permanent,
              selectType == 3,
            ),
            onTap: () {
              setState(() {
                selectType = 3;
              });
            },
          ),
          SizedBox(height: 13.w),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SizedBox(width: 20.w),
              GestureDetector(
                child: Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 12.w,
                    vertical: 5.w,
                  ),
                  child: text(
                    SCAppLocalizations.of(context)!.cancel,
                    fontSize: 14.sp,
                    textColor: Colors.grey,
                  ),
                ),
                onTap: () {
                  SmartDialog.dismiss(tag: "showKickedOutOfRoomDialog");
                },
              ),
              Spacer(),
              SCDebounceWidget(
                child: Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 12.w,
                    vertical: 5.w,
                  ),
                  child: text(
                    SCAppLocalizations.of(context)!.confirm,
                    fontSize: 14.sp,
                    textColor: Colors.black,
                  ),
                ),
                onTap: () async {
                  if (selectType > -1) {
                    String roomId =
                        Provider.of<RealTimeCommunicationManager>(
                          context,
                          listen: false,
                        ).currenRoom?.roomProfile?.roomProfile?.id ??
                        "";
                    if (selectType == 0) {
                      await SCChatRoomRepository().joinBlacklist(
                        roomId,
                        widget.userId,
                        5,
                      );
                      SCTts.show(
                        SCAppLocalizations.of(context)!.operationSuccessful,
                      );
                      SmartDialog.dismiss(tag: "showKickedOutOfRoomDialog");
                    } else if (selectType == 1) {
                      await SCChatRoomRepository().joinBlacklist(
                        roomId,
                        widget.userId,
                        1440,
                      );
                      SCTts.show(
                        SCAppLocalizations.of(context)!.operationSuccessful,
                      );
                      SmartDialog.dismiss(tag: "showKickedOutOfRoomDialog");
                    } else if (selectType == 2) {
                      await SCChatRoomRepository().joinBlacklist(
                        roomId,
                        widget.userId,
                        43200,
                      );
                      SCTts.show(
                        SCAppLocalizations.of(context)!.operationSuccessful,
                      );
                      SmartDialog.dismiss(tag: "showKickedOutOfRoomDialog");
                    } else if (selectType == 3) {
                      await SCChatRoomRepository().joinBlacklist(
                        roomId,
                        widget.userId,
                        5184000,
                      );
                      SCTts.show(
                        SCAppLocalizations.of(context)!.operationSuccessful,
                      );
                      SmartDialog.dismiss(tag: "showKickedOutOfRoomDialog");
                    }
                  }
                },
              ),
              SizedBox(width: 20.w),
            ],
          ),
          SizedBox(height: 20.w),
        ],
      ),
    );
  }

  _buildItem(String time, bool isSelect) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 5.w, vertical: 6.w),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(20),
        color: Colors.transparent,
        border: Border.all(color: SocialChatTheme.textSecondary, width: 1.w),
      ),
      width: 155.w,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(width: 3.w),
          Image.asset(
            isSelect
                ? "sc_images/login/sc_icon_login_ser_select.png"
                : "sc_images/login/sc_icon_login_ser_select_un.png",
            width: 16.w,
            height: 16.w,
          ),
          SizedBox(width: 10.w),
          text(time, fontSize: 14.sp, textColor: Colors.black),
        ],
      ),
    );
  }
}
