import 'dart:convert';

import 'package:extended_text/extended_text.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'package:yumi/app_localizations.dart';
import 'package:yumi/ui_kit/components/appbar/socialchat_appbar.dart';
import 'package:yumi/ui_kit/components/sc_compontent.dart';
import 'package:yumi/app/constants/sc_screen.dart';
import 'package:yumi/app/routes/sc_fluro_navigator.dart';
import 'package:yumi/shared/tools/sc_date_utils.dart';
import 'package:yumi/shared/data_sources/sources/repositories/sc_user_repository_impl.dart';
import 'package:yumi/shared/business_logic/models/res/sc_public_message_page_res.dart';
import 'package:yumi/services/audio/rtm_manager.dart';
import 'package:yumi/modules/index/main_route.dart';
import 'package:yumi/app/constants/sc_global_config.dart';
import 'package:yumi/app/config/business_logic_strategy.dart';

class MessageNotifcationPage extends StatefulWidget {
  @override
  _MessageNotifcationPageState createState() => _MessageNotifcationPageState();
}

class _MessageNotifcationPageState extends State<MessageNotifcationPage> {
  List<Records> records = [];
  num index = 1;
  final RefreshController _refreshController = RefreshController();
  final ScrollController _scrollController = ScrollController();
  RtmProvider? rtmProvider;

  BusinessLogicStrategy get _strategy => SCGlobalConfig.businessLogicStrategy;

  @override
  void initState() {
    super.initState();
    rtmProvider = Provider.of<RtmProvider>(context, listen: false);
    rtmProvider?.onNewNotifcationMessageCurrentConversationListener =
        _onNewMessage;
    loadData();
  }

  @override
  void dispose() {
    rtmProvider?.onNewNotifcationMessageCurrentConversationListener = null;
    super.dispose();
  }

  _onNewMessage(Records? message) async {
    if (message == null) {
      return;
    }

    int? index;
    for (var element in records) {
      if (element.id == message.id) {
        index = records.indexOf(element);
        continue;
      }
    }
    if (index != null) {
      records.removeAt(index);
      records.insert(index, message);
    } else {
      records.insert(0, message);
    }
    _scrollController.jumpTo(0.0);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Image.asset(
          _strategy.getSCMessageChatPageRoomSettingBackground(),
          width: ScreenUtil().screenWidth,
          height: ScreenUtil().screenHeight,
          fit: BoxFit.fill,
        ),
        Scaffold(
          backgroundColor: Colors.transparent,
          resizeToAvoidBottomInset: false,
          appBar: SocialChatStandardAppBar(
            title: SCAppLocalizations.of(context)!.notifcation,
            actions: [],
          ),
          body: SafeArea(
            top: false,
            child: SmartRefresher(
              enablePullDown: false,
              enablePullUp: true,
              onLoading: () async {
                index = index + 1;
                loadData();
              },
              footer: CustomFooter(
                height: 1,
                builder: (context, mode) {
                  return SizedBox(
                    height: 1,
                    width: 1,
                    child: SizedBox(height: 1, width: 1),
                  );
                },
              ),
              controller: _refreshController,
              child:
                  records.isNotEmpty
                      ? Container(
                        child: CustomScrollView(
                          shrinkWrap: records.length > 3 ? false : true,
                          controller: _scrollController,
                          reverse: true,
                          physics: const ClampingScrollPhysics(),
                          // 禁用回弹效果
                          slivers: [
                            SliverList(
                              delegate: SliverChildBuilderDelegate(
                                (c, i) => _MessageItem(message: records[i]),
                                childCount: records.length,
                              ),
                            ),
                          ],
                        ),
                      )
                      : mainEmpty(),
            ),
          ),
        ),
      ],
    );
  }

  void loadData() {
    SCAccountRepository().publicMessagePage("notification", index, 30).then((
      result,
    ) {
      var list = result.records ?? [];
      if (list.isNotEmpty) {
        records.addAll(list);
        if (list.length == 30) {
          _refreshController.loadComplete();
        } else {
          _refreshController.loadNoData();
        }
      } else {
        _refreshController.loadNoData();
      }
      setState(() {});
      _scrollController.jumpTo(0.0);
    });
  }
}

class _MessageItem extends StatelessWidget {
  final Records message;
  late BuildContext context;

  _MessageItem({required this.message});

  @override
  Widget build(BuildContext context) {
    this.context = context;
    print('status:${message.status}');
    String time = SCMDateUtils.formatMessageTime(
      context,
      DateTime.fromMillisecondsSinceEpoch(int.parse(message.createdAt ?? "0")),
    );
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 15.w, vertical: 8.w),
      child: Column(
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(bottom: 12.w),
            child: Row(
              children: <Widget>[
                Spacer(),
                Container(
                  decoration: BoxDecoration(
                    color: Colors.black12,
                    borderRadius: BorderRadius.all(Radius.circular(height(13))),
                  ),
                  alignment: Alignment.center,
                  padding: EdgeInsets.symmetric(
                    horizontal: width(15),
                    vertical: 8.w,
                  ),
                  child: Text(
                    time,
                    style: TextStyle(
                      fontSize: sp(12),
                      color: Colors.white,
                      fontWeight: FontWeight.w400,
                      decoration: TextDecoration.none,
                      height: 1,
                    ),
                  ),
                ),
                Spacer(),
              ],
            ),
          ),
          _msg(message),
        ],
      ),
    );
  }

  _msg(Records message) {
    return GestureDetector(
      child: Container(
        alignment: AlignmentDirectional.centerStart,
        decoration: BoxDecoration(
          color: Color(0xff18F2B1).withOpacity(0.1),
          borderRadius: BorderRadius.all(Radius.circular(8)),
        ),
        padding: EdgeInsets.all(8.0.w),
        child: Column(
          children: [
            Row(
              children: [
                SizedBox(width: 5.w),
                Expanded(
                  child: ExtendedText(
                    message.title ?? "",
                    overflow: TextOverflow.ellipsis,
                    maxLines: 2,
                    // specialTextSpanBuilder: MySpecialTextSpanBuilder(),
                    style: TextStyle(
                      fontSize: sp(16),
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                SizedBox(width: 5.w),
              ],
            ),
            message.imageUrl != null && message.imageUrl!.isNotEmpty
                ? GestureDetector(
                  child: Container(
                    margin: EdgeInsets.all(5.w),
                    child: netImage(
                      url: message.imageUrl ?? "",
                      fit: BoxFit.contain,
                      borderRadius: BorderRadius.all(Radius.circular(8)),
                    ),
                  ),
                  onTap: () {
                    String encodedUrls = Uri.encodeComponent(
                      jsonEncode([message.imageUrl]),
                    );
                    SCNavigatorUtils.push(
                      context,
                      "${SCMainRoute.imagePreview}?imageUrls=$encodedUrls&initialIndex=0",
                    );
                  },
                )
                : Container(),
            Row(
              children: [
                SizedBox(width: 5.w),
                Expanded(
                  child: ExtendedText(
                    message.content ?? "",
                    // specialTextSpanBuilder: MySpecialTextSpanBuilder(),
                    style: TextStyle(fontSize: sp(14), color: Colors.white),
                  ),
                ),
                SizedBox(width: 5.w),
              ],
            ),
          ],
        ),
      ),
      onTap: () {
        if (message.extraData != null && message.extraData?.link != null) {
          if (message.extraData!.link!.startsWith("http") ||
              message.extraData!.link!.startsWith("https")) {
            SCNavigatorUtils.push(
              context,
              "${SCMainRoute.webViewPage}?url=${Uri.encodeComponent(message.extraData?.link ?? "")}&showTitle=false",
              replace: false,
            );
          }
        }
      },
    );
  }
}
