import 'package:easy_localization/easy_localization.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:telnow_mobile_new/src/layouts/functions/message.dart';
import 'package:telnow_mobile_new/src/layouts/mobile/message_chat.dart';
import 'package:telnow_mobile_new/src/layouts/components/template.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';
import 'package:telnow_mobile_new/src/utils/provider.dart';

class MobMessageListPage extends StatefulWidget {
  Map<String, dynamic>? user;
  MobMessageListPage(this.user, {super.key});

  @override
  State<MobMessageListPage> createState() => _MobMessageListPageState();
}

class _MobMessageListPageState extends State<MobMessageListPage> {
  final MessageFunction messageFunc = MessageFunction();
  
  @override
  void initState() {
    Provider.of<MessageModule>(context, listen: false).reset();
    if(widget.user == null){
      messageFunc.getUser(context);
    }
    else{
      Provider.of<MessageModule>(context, listen: false).setUser(widget.user!);
      messageFunc.getDataMessages(context);
    }
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: appBarTemplate(context: context, title: 'message'.tr()),
      body: Column(
        children: [
          divider(),
          Expanded(
            child: Container(
              alignment: Alignment.topCenter,
              width: U.bodyWidth(context),
              child: EasyRefresh(
                header: MaterialHeader(clamping: true, color: primaryColor),
                onRefresh: () => messageFunc.onRefresh(context),
                child: Provider.of<MessageModule>(context).data().isEmpty && !Provider.of<MessageModule>(context).firstLoad()? loadingTemplate(() {},) : Provider.of<MessageModule>(context).data().isEmpty ? Center(
                  child: Text('noMessageText').tr(),
                ) : ListView(
                  padding: EdgeInsets.only(top: 12.0),
                  children: List.generate(Provider.of<MessageModule>(context).data().length, (i) {
                    bool _isMe = Provider.of<MessageModule>(context, listen: false).data()[i]['userId'] == Provider.of<MessageModule>(context, listen: false).user()['userId'] ? true : false;
                    return GestureDetector(
                        child: Container(
                          child: ListTile(
                            leading: Provider.of<MessageModule>(context).data()[i]['senderAvatar'] != null && Provider.of<MessageModule>(context).data()[i]['senderAvatar'] != '' ? CircleAvatar(
                              backgroundImage: NetworkImage(Provider.of<MessageModule>(context).data()[i]['senderAvatar']),
                              radius: 24,
                            ) : Container(
                              height: 48,
                              width: 48,
                              child: Center(child: Text(_isMe ? Provider.of<MessageModule>(context).data()[i]['recipientName'] == "all_informants" ? "allInformants".tr()[0] : Provider.of<MessageModule>(context).data()[i]['recipientName'][0] : Provider.of<MessageModule>(context).data()[i]['senderName'][0], style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 18))),
                              decoration: BoxDecoration(shape: BoxShape.circle, color: Color(U.getColor(_isMe ? Provider.of<MessageModule>(context).data()[i]['recipient'] : Provider.of<MessageModule>(context).data()[i]['recipientId']))),
                            ),
                            title: Text(_isMe ? Provider.of<MessageModule>(context).data()[i]['recipientName'] == "all_informants" ? "allInformants".tr() : Provider.of<MessageModule>(context).data()[i]['recipientName'] : Provider.of<MessageModule>(context).data()[i]['senderName']),
                            subtitle: Row(
                              children: [
                                _isMe ? Padding(
                                  padding: EdgeInsets.only(right: 4),
                                  child: Icon(Icons.done_all, size: 18, color: Colors.blueGrey),
                                ) : Container(),
                                Provider.of<MessageModule>(context).data()[i]['isImage'] ? Align(
                                  alignment: Alignment.centerLeft,
                                  child: Row(
                                    children: [
                                      Icon(Provider.of<MessageModule>(context).data()[i]['fileType'] == 'pdf' ? Icons.picture_as_pdf : Icons.image, color: Colors.black45, size: 16),
                                      SizedBox(width: 6),
                                      Provider.of<MessageModule>(context).data()[i]['lastText'] == '' ? Provider.of<MessageModule>(context).data()[i]['fileType'] == 'pdf' ? Text('pdfFile'.tr()) : Text('photo'.tr()) : Container()
                                    ],
                                  ),
                                ) : Container(),
                                Expanded(
                                  child: Text(Provider.of<MessageModule>(context).data()[i]['lastText'], style: TextStyle(fontSize: 13), maxLines: 1, overflow: TextOverflow.ellipsis),
                                )
                              ],
                            ),
                            trailing: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: [
                                Text(messageFunc.timeSet(Provider.of<MessageModule>(context).data()[i]['lastDateTimeSend']), style: TextStyle(fontSize: 11, color: Provider.of<MessageModule>(context).data()[i]['lastReadStatus'] == 'UNREAD' && !_isMe ? Colors.green : Colors.black45)),
                                SizedBox(height: 4),
                                Icon(Icons.circle, color: Colors.green.withValues(alpha: Provider.of<MessageModule>(context).data()[i]['lastReadStatus'] == 'UNREAD' && !_isMe ? 1 : 0))
                              ],
                            ),
                          ),
                        ),
                        onTap: () async {
                          navigateTo(context, MobMessageChatPage(Provider.of<MessageModule>(context, listen: false).user(), Provider.of<MessageModule>(context, listen: false).data()[i]['chatId'], _isMe ? Provider.of<MessageModule>(context, listen: false).data()[i]['recipientName'] : Provider.of<MessageModule>(context, listen: false).data()[i]['senderName'], Provider.of<MessageModule>(context, listen: false).data()[i]['id'].toString(), _isMe, Provider.of<MessageModule>(context, listen: false).data()[i]['recipient']));
                          messageFunc.onRefresh(context);
                        });
                    })
                ),
              ),
            ),
          )
        ],
      ),
      floatingActionButton: Provider.of<MessageModule>(context).user().isNotEmpty && Provider.of<MessageModule>(context).user()['canSendMessage'] ? FloatingActionButton(
        child: U.iconsax('message', color: Colors.white),
        backgroundColor: primaryColor,
        onPressed: () => messageFunc.createMessage(context),
      ):null,
    );
  }
}
