import 'package:chat/services/tim/message_service.dart';
import 'package:chat/views/conversation/widgets/message_widget.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:scroll_to_index/scroll_to_index.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_conversation.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';

class MessageArea extends StatefulWidget {
  final V2TimConversation conversation;

  const MessageArea(this.conversation, {Key? key}) : super(key: key);

  @override
  State<MessageArea> createState() => _MessageAreaState();
}

class _MessageAreaState extends State<MessageArea> {
  late AutoScrollController _scrollController;
  String? _lastMessageId;

  @override
  void initState() {
    super.initState();
    _scrollController = AutoScrollController(
      viewportBoundaryGetter: () => Rect.fromLTRB(
        0,
        0,
        0,
        MediaQuery.of(context).padding.bottom,
      ),
      axis: Axis.vertical,
    );

    _loadMessages();
  }

  Future<void> _loadMessages() async {
    TimMessageService.to
        .loadMessagesFromService(
      widget.conversation,
      _lastMessageId,
      _scrollController,
    )
        .then((value) {
      _lastMessageId = value;
    });
  }

  @override
  Widget build(BuildContext context) {
    return GetX<TimMessageService>(builder: (service) {
      return ListView.separated(
        scrollDirection: Axis.vertical,
        controller: _scrollController,
        shrinkWrap: true,
        physics: const ClampingScrollPhysics(),
        padding: const EdgeInsets.all(8),
        reverse: true,
        cacheExtent: 1200,
        addAutomaticKeepAlives: true,
        itemCount: service.messages.length,
        itemBuilder: (_, index) {
          V2TimMessage? message = service.messages[index];
          return AutoScrollTag(
            key: ValueKey(index),
            controller: _scrollController,
            index: index,
            child: MessageWidget(message),
          );
        },
        separatorBuilder: (c, i) {
          return Container(
            height: 8,
          );
        },
      );
    });
  }
}
