import 'package:chat/services/tim/message_service.dart';
import 'package:chat/widgets/custom_easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.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';
import 'message_widget.dart';

class MessageList extends StatefulWidget {
  final V2TimConversation conversation;

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

  @override
  State<MessageList> createState() => _MessageListState();
}

class _MessageListState extends State<MessageList> {
  final EasyRefreshController _refreshController = EasyRefreshController();
  late AutoScrollController _scrollController;
  String? _lastMessageId;
  bool isFirst = true;

  @override
  void dispose() {
    super.dispose();
  }

  @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 EasyRefresh(
        controller: _refreshController,
        header: CustomEasyRefresh.header,
        footer: CustomEasyRefresh.footer,
        firstRefresh: false,
        onRefresh: _loadMessages,
        child: ListView.separated(
          scrollDirection: Axis.vertical,
          controller: _scrollController,
          shrinkWrap: true,
          physics: const ClampingScrollPhysics(),
          padding: const EdgeInsets.only(
            left: 8,
            right: 8,
            top: 8,
            bottom: 8,
          ),
          reverse: false,
          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,
            );
          },
        ),
      );
    });
  }
}
