
import 'package:flutter/material.dart';
import 'package:jiffy/jiffy.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../../api/marianumcloud/talk/chat/richObjectStringProcessor.dart';
import '../../../../api/marianumcloud/talk/leaveRoom/leaveRoom.dart';
import '../../../../api/marianumcloud/talk/room/getRoomResponse.dart';
import '../../../../api/marianumcloud/talk/setFavorite/setFavorite.dart';
import '../../../../api/marianumcloud/talk/setReadMarker/setReadMarker.dart';
import '../../../../api/marianumcloud/talk/setReadMarker/setReadMarkerParams.dart';
import '../../../../model/chatList/chatProps.dart';
import '../../../../widget/confirmDialog.dart';
import '../../../../widget/debug/debugTile.dart';
import '../../../../widget/userAvatar.dart';
import '../chatView.dart';
import '../talkNavigator.dart';

class ChatTile extends StatefulWidget {
  final GetRoomResponseObject data;
  final void Function({bool renew}) query;
  final bool disableContextActions;
  final bool hasDraft;

  const ChatTile({super.key, required this.data, required this.query, this.disableContextActions = false, this.hasDraft = false});

  @override
  State<ChatTile> createState() => _ChatTileState();
}

class _ChatTileState extends State<ChatTile> {
  late String selfUsername;

  @override
  void initState() {
    super.initState();
    SharedPreferences.getInstance().then((value) => {
      selfUsername = value.getString('username')!
    });
  }

  void setCurrentAsRead() {
    SetReadMarker(
        widget.data.token,
        true,
        setReadMarkerParams: SetReadMarkerParams(
            lastReadMessage: widget.data.lastMessage.id
        )
    ).run().then((value) => widget.query(renew: true));
  }

  @override
  Widget build(BuildContext context) => Consumer<ChatProps>(builder: (context, chatData, child) {
    var isGroup = widget.data.type != GetRoomResponseObjectConversationType.oneToOne;
    var circleAvatar = UserAvatar(id: isGroup ? widget.data.token : widget.data.name, isGroup: isGroup);
    return ListTile(
        style: ListTileStyle.list,
        tileColor: chatData.currentToken() == widget.data.token && TalkNavigator.isSecondaryVisible(context)
            ? Theme.of(context).primaryColor.withAlpha(100)
            : null,
        leading: Stack(
          children: [
            circleAvatar,
            Visibility(
              visible: widget.data.isFavorite,
              child: Positioned(
                right: 0,
                bottom: 0,
                child: Container(
                  padding: const EdgeInsets.all(1),
                  decoration: BoxDecoration(
                    color: Theme.of(context).primaryColor.withAlpha(200),
                    borderRadius: BorderRadius.circular(90.0),
                  ),
                  child: const Icon(Icons.star, color: Colors.amberAccent, size: 15),
                ),
              ),
            )
          ],
        ),
        title: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Flexible(
              child: Text(widget.data.displayName, overflow: TextOverflow.ellipsis),
            ),
            if(widget.hasDraft) ...[
              const SizedBox(width: 5),
              const Icon(Icons.edit_outlined, size: 15),
            ],
          ],
        ),
        subtitle: Text("${Jiffy.parseFromMillisecondsSinceEpoch(widget.data.lastMessage.timestamp * 1000).fromNow()}: ${RichObjectStringProcessor.parseToString(widget.data.lastMessage.message.replaceAll("\n", " "), widget.data.lastMessage.messageParameters)}", overflow: TextOverflow.ellipsis),
        trailing: widget.data.unreadMessages <= 0
            ? null
            : Container(
          padding: const EdgeInsets.all(1),
          decoration: BoxDecoration(
            color: Theme.of(context).primaryColor,
            borderRadius: BorderRadius.circular(30),
          ),
          constraints: const BoxConstraints(
            minWidth: 20,
            minHeight: 20,
          ),
          child: Text(
            '${widget.data.unreadMessages}',
            style: const TextStyle(
              color: Colors.white,
              fontSize: 15,
            ),
            textAlign: TextAlign.center,
          ),
        ),
        onTap: () async {
          setCurrentAsRead();
          var view = ChatView(room: widget.data, selfId: selfUsername, avatar: circleAvatar);
          TalkNavigator.pushSplitView(context, view, overrideToSingleSubScreen: true);
          Provider.of<ChatProps>(context, listen: false).setQueryToken(widget.data.token);
        },
        onLongPress: () {
          if(widget.disableContextActions) return;
          showDialog(context: context, builder: (context) => SimpleDialog(
            children: [
              Visibility(
                visible: widget.data.unreadMessages > 0,
                replacement: ListTile(
                  leading: const Icon(Icons.mark_chat_unread_outlined),
                  title: const Text('Als ungelesen markieren'),
                  onTap: () {
                    SetReadMarker(widget.data.token, false).run().then((value) => widget.query(renew: true));
                    Navigator.of(context).pop();
                  },
                ),
                child: ListTile(
                  leading: const Icon(Icons.mark_chat_read_outlined),
                  title: const Text('Als gelesen markieren'),
                  onTap: () {
                    setCurrentAsRead();
                    Navigator.of(context).pop();
                  },
                ),
              ),
              Visibility(
                visible: widget.data.isFavorite,
                replacement: ListTile(
                  leading: const Icon(Icons.star_outline),
                  title: const Text('Zu Favoriten hinzufügen'),
                  onTap: () {
                    SetFavorite(widget.data.token, true).run().then((value) => widget.query(renew: true));
                    Navigator.of(context).pop();
                  },
                ),
                child: ListTile(
                  leading: const Icon(Icons.stars_outlined),
                  title: const Text('Von Favoriten entfernen'),
                  onTap: () {
                    SetFavorite(widget.data.token, false).run().then((value) => widget.query(renew: true));
                    Navigator.of(context).pop();
                  },
                ),
              ),
              ListTile(
                leading: const Icon(Icons.delete_outline),
                title: const Text('Konversation verlassen'),
                onTap: () {
                  ConfirmDialog(
                    title: 'Chat verlassen',
                    content: 'Du benötigst ggf. eine Einladung um erneut beizutreten.',
                    confirmButton: 'Löschen',
                    onConfirm: () {
                      LeaveRoom(widget.data.token).run().then((value) => widget.query(renew: true));
                      Navigator.of(context).pop();
                    },
                  ).asDialog(context);
                },
              ),
              DebugTile(context).jsonData(widget.data.toJson()),
            ],
          ));
        },
      );
  });
}
