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/C.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';
import 'package:telnow_mobile_new/src/utils/provider.dart';

import 'history_forum.dart';

class MobMessageListPage extends StatefulWidget {
  final Map<String, dynamic>? user;
  const 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 {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        Provider.of<MessageModule>(context, listen: false).setUser(widget.user!);
      });
      messageFunc.getDataMessages(context);
    }
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Widget chat(){
      return 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()? loadingTemplateNoVoid() : 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);
                          });
                    })
                ),
              ),
            ),
          )
        ],
      );
    }

    Widget forum(){
      return Column(
        children: [
          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).forum().isEmpty && !Provider.of<MessageModule>(context).firstLoad()? loadingTemplateNoVoid() : Provider.of<MessageModule>(context).forum().isEmpty ? Center(
                  child: Text('noMessageText').tr(),
                ) : ListView(
                  padding: EdgeInsets.only(top: 16.0),
                  children: List.generate(Provider.of<MessageModule>(context).forum().length, (i){
                    return GestureDetector(
                      onTap: (){
                        navigateTo(context, MobHistoryForumPage(data: Provider.of<MessageModule>(context, listen: false).forum()[i]['ticket'])).then((_){
                          messageFunc.getDataForum(context);
                        });
                      },
                      child: Container(
                        decoration: BoxDecoration(
                          color: Colors.white,
                        ),
                        width: double.infinity,
                        child: Column(
                          children: [
                            Padding(
                              padding: const EdgeInsets.all(12.0),
                              child: Row(
                                children: [
                                  Container(
                                    height: 50,
                                    width: 50,
                                    decoration: BoxDecoration(
                                      image: Provider.of<MessageModule>(context).forum()[i]['ticket']['_requestImage'] != null && Provider.of<MessageModule>(context).forum()[i]['ticket']['_requestImage'].isNotEmpty
                                          ? DecorationImage(image: NetworkImage(Provider.of<MessageModule>(context).forum()[i]['ticket']['_requestImage']))
                                          : null,
                                      border: Border.all(color: Colors.black12),
                                      borderRadius: BorderRadius.circular(50),
                                    ),
                                  ),
                                  SizedBox(width: 12,),
                                  ConstrainedBox(
                                    constraints: BoxConstraints(
                                      maxWidth: MediaQuery.of(context).size.width - (16*2+12+50),
                                    ),
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            Flexible(
                                              child: Text(
                                                Provider.of<MessageModule>(context).forum()[i]['ticket'][U.langColumn(context, 'requestSubject')] ?? "",
                                                maxLines: 1,
                                                overflow: TextOverflow.ellipsis,
                                                softWrap: false,
                                                style: TextStyle(
                                                  fontWeight: FontWeight.w600,
                                                ),
                                              ),
                                            ),
                                            SizedBox(width: 8),
                                            Text(
                                              convertDate(Provider.of<MessageModule>(context).forum()[i]['datetime'], context.locale.toString()),
                                              style: TextStyle(
                                                fontSize: 12,
                                                fontWeight: Provider.of<MessageModule>(context).forum()[i]['readStatus']=='UNREAD' ? FontWeight.w600 : FontWeight.w300,
                                                color: Provider.of<MessageModule>(context).forum()[i]['readStatus']=='UNREAD' ? primaryColor : Colors.black,
                                              ),
                                            ),
                                          ],
                                        ),
                                        SizedBox(height: 8,),
                                        Row(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                          children: [
                                            Flexible(
                                              child: Text(
                                                Provider.of<MessageModule>(context).forum()[i]['msg'],
                                                overflow: TextOverflow.ellipsis,
                                                maxLines: 2,
                                              ),
                                            ),
                                            SizedBox(width: 12,),
                                            Provider.of<MessageModule>(context).forum()[i]['readStatus']=='UNREAD' ? Container(
                                              width: 12,
                                              height: 12,
                                              decoration: BoxDecoration(
                                                borderRadius: BorderRadius.all(Radius.circular(12)),
                                                color: primaryColor
                                              ),
                                            ):SizedBox()
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            Container(
                              padding: EdgeInsets.only(top: 16),
                              height: 8,
                              decoration: BoxDecoration(
                                  color: Color(0xFFF3F3F3)
                              ),
                            )
                          ],
                        )
                      ),
                    );
                  }),
                )
              ),
            ),
          ),
        ],
      );
    }

    Widget tabForum(){
      return Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          GestureDetector(
            onTap: () {
              Provider.of<MessageModule>(context, listen: false).setActiveTab(0);
            },
            child: Container(
              margin: EdgeInsets.only(left: 16),
              padding: EdgeInsets.symmetric(vertical: 5, horizontal: 16),
              decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border(bottom: BorderSide(color: Provider.of<MessageModule>(context).activeTab() == 0 ? primaryColor : primaryColor.withValues(alpha: 0.3), width: Provider.of<MessageModule>(context).activeTab() == 0 ? 2 : 1))),
              child: Text('chat'.tr(), style: TextStyle(color: Provider.of<MessageModule>(context).activeTab() == 0 ? textColor : textColor.withValues(alpha: 0.65), fontSize: 16)),
            ),
          ),
          GestureDetector(
            onTap: () {
              Provider.of<MessageModule>(context, listen: false).setActiveTab(1);
            },
            child: Container(
              padding: EdgeInsets.symmetric(vertical: 5, horizontal: 16),
              decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border(bottom: BorderSide(color: Provider.of<MessageModule>(context).activeTab() == 1 ? primaryColor : primaryColor.withValues(alpha: 0.3), width: Provider.of<MessageModule>(context).activeTab() == 1 ? 2 : 1))),
              child: Text('forum'.tr(), style: TextStyle(color: Provider.of<MessageModule>(context).activeTab() == 1 ? textColor : textColor.withValues(alpha: 0.65), fontSize: 16)),
            ),
          ),
        ],
      );
    }

    Widget bodyForum(){
      return Column(
        children: [
          divider(padding: EdgeInsets.only(bottom: 12)),
          tabForum(),
          SizedBox(height: 12,),
          Expanded(
            child: Provider.of<MessageModule>(context).activeTab() == 0 ? chat() : forum(),
          )
        ]
      );
    }

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: appBarTemplate(context: context, title: 'message'.tr()),
      body: bodyForum(),
      floatingActionButton: Provider.of<MessageModule>(context).user().isNotEmpty &&
          Provider.of<MessageModule>(context).user()['canSendMessage'] &&
          Provider.of<MessageModule>(context).activeTab() == 0 ? FloatingActionButton(
        backgroundColor: primaryColor,
        onPressed: () => messageFunc.createMessage(context),
        child: U.iconsax('message', color: Colors.white),
      ):null,
    );
  }
}
