import 'package:flutter/material.dart';
import 'package:jiffy/jiffy.dart';
import 'package:persistent_bottom_nav_bar/persistent_tab_view.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/endpointData.dart';
import '../../../widget/confirmDialog.dart';
import '../../../widget/debug/debugTile.dart';
import 'chatView.dart';

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

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

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

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

  @override
  void initState() {
    super.initState();
    SharedPreferences.getInstance().then((value) => {
      username = 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) {
    bool useRemotePicture = widget.data.type == GetRoomResponseObjectConversationType.oneToOne;
    CircleAvatar circleAvatar = CircleAvatar(
      foregroundImage: useRemotePicture ? Image.network("https://${EndpointData().nextcloud().full()}/avatar/${widget.data.name}/128").image : null,
      backgroundColor: Theme.of(context).primaryColor,
      foregroundColor: Colors.white,
      onForegroundImageError: useRemotePicture ? (o, t) {} : null,
      child: widget.data.type == GetRoomResponseObjectConversationType.group ? const Icon(Icons.group) : const Icon(Icons.person),
    );

    return ListTile(
      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: Text(widget.data.displayName),
      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: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Visibility(
            visible: widget.data.unreadMessages > 0,
            child: 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();
        PersistentNavBarNavigator.pushNewScreen(
            context,
            screen: ChatView(room: widget.data, selfId: username, avatar: circleAvatar),
            withNavBar: false
        );
      },
      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(widget.data.toJson()).asTile(context),
          ],
        ));
      },
    );
  }
}
