import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:lottie/lottie.dart';
import 'package:taafee_mobile/common/const/const.dart';
import 'package:taafee_mobile/common/extensions/widget_extension.dart';
import 'package:taafee_mobile/common/widgets/text.dart';
import 'package:taafee_mobile/features/chat/business%20logic%20layer/chat_controller.dart';
import 'package:taafee_mobile/features/chat/presentation_layer/widgets/chat_widget.dart';
import 'package:taafee_mobile/features/home/presentation_layer/widgets/search_bar.dart';
import '../../../../common/widgets/loader.dart';
import '../../../../core/utils/utils.dart';

// ignore: must_be_immutable
class ChatScreen extends StatelessWidget {
  ChatScreen({super.key});
  final ChatController chatController = Get.find<ChatController>();
  Timer? debouncer;
  TextEditingController searchFieldController = TextEditingController();
  ScrollController scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    String lastDate = 'today'.tr;
    if (chatController.rooms.result.data.isEmpty) {
      chatController.getRooms();
    }
    scrollController.addListener(() {
      if (scrollController.position.atEdge && scrollController.offset != 0) {
        if (searchFieldController.text != '') {
          chatController.getRooms(searchQuery: searchFieldController.text);
        } else {
          chatController.getRooms();
        }
      }
    });

    return Scaffold(
      backgroundColor: AppColors.backGroundColor,
      body: RefreshIndicator(
        onRefresh: () async {
          if (chatController.rooms.hasError) {
            await chatController.getRooms();
          }
        },
        child: SingleChildScrollView(
          controller: scrollController,
          physics: const BouncingScrollPhysics(),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              BoldTextWidget(
                "chats".tr,
                color: AppColors.textColor,
                fontSize: 18,
              ).paddingOnly(top: 30),
              SearchBarWidget(
                controller: searchFieldController,
                onChanged: (value) {
                  lastDate = 'today'.tr;

                  if (debouncer?.isActive ?? false) {
                    debouncer!.cancel();
                  }
                  debouncer = Timer(const Duration(seconds: 1), () async {
                    await chatController.getRooms(
                        searchQuery: value, specificPage: 1);
                  });
                },
                onSearch: () {},
                hint: "search_chat".tr,
                radius: 7,
              ),
              Obx(() {
                if (chatController.rooms.result.data.isNotEmpty) {
                  return RegularTextWidget(
                    Utils.formatDateDifference(
                        chatController.rooms.result.data[0].lastMessageDate),
                  ).paddingSymmetric(vertical: 20);
                }
                return Container();
              }),
              Obx(() {
                if (chatController.rooms.hasError) {
                  return SizedBox(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Lottie.asset(
                          'assets/animations/Wifi.json',
                          repeat: false,
                          width: 120,
                        ).paddingAll(5).paddingOnly(top: 80),
                        RegularTextWidget(
                          'you_have_no_internet_connection'.tr,
                          textAlign: TextAlign.center,
                          color: AppColors.textColor,
                          fontSize: 18.0,
                        ).paddingOnly(bottom: Get.height),
                      ],
                    ).center(),
                  ).center();
                }
                if (chatController.connectionState.value ==
                    SocketConnectionState.connected) {
                  if (chatController.rooms.loading &&
                      chatController.rooms.result.data.isEmpty) {
                    return SizedBox(height: 300, child: Loader().center());
                  }
                  if (chatController.connectionState.value ==
                          SocketConnectionState.connected &&
                      !chatController.rooms.loading &&
                      chatController.rooms.result.data.isEmpty) {
                    return Column(
                      children: [
                        Lottie.asset(
                          'assets/animations/folder.json',
                          repeat: false,
                        ),
                        if (searchFieldController.text == '')
                          RegularTextWidget('no_previous_conversations_!'.tr),
                        if (searchFieldController.text == '')
                          RegularTextWidget(
                              'add_some_by_contact_with_others'.tr),
                        if (searchFieldController.text != '')
                          RegularTextWidget('no_results_found'.tr)
                      ],
                    );
                  }
                  return Obx(() {
                    return ListView.separated(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemBuilder: (BuildContext context, index) {
                        return ChatWidget(
                            room: chatController.rooms.result.data[index],
                            onBack: () {
                              lastDate = 'today'.tr;
                            });
                      },
                      separatorBuilder: (BuildContext context, index) {
                        //  return Container();
                        if (chatController
                                .rooms.result.data[index].lastMessageDate.day !=
                            chatController.rooms.result.data[index + 1]
                                .lastMessageDate.day) {
                          String dateDifference = Utils.formatDateDifference(
                              chatController.rooms.result.data[index + 1]
                                  .lastMessageDate);
                          if (dateDifference == lastDate) {
                            return Divider(
                              color: AppColors.dividerColor,
                              thickness: 2,
                            ).paddingSymmetric(horizontal: 20);
                          }
                          // if (dateDifference == 'last_week'.tr &&
                          //     ((chatController.rooms.result.data[index]
                          //             .lastMessageDate.weekday <
                          //         chatController.rooms.result.data[index + 1]
                          //             .lastMessageDate.weekday))) {
                          //   return Divider(
                          //     color: AppColors.dividerColor,
                          //     thickness: 2,
                          //   ).paddingSymmetric(horizontal: 20);
                          // }
                          lastDate = dateDifference;
                          return RegularTextWidget(
                            dateDifference,
                          ).paddingSymmetric(vertical: 20);
                        }

                        return Divider(
                          color: AppColors.dividerColor,
                          thickness: 2,
                        ).paddingSymmetric(horizontal: 20);
                      },
                      itemCount: chatController.rooms.result.data.length,
                    );
                  });
                } else {
                  if (chatController.connectionState.value ==
                      SocketConnectionState.error) {
                    return SizedBox(
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Lottie.asset(
                            'assets/animations/Wifi.json',
                            repeat: false,
                            width: 120,
                          ).paddingAll(5).paddingOnly(top: 80),
                          RegularTextWidget(
                            'you_have_no_internet_connection'.tr,
                            textAlign: TextAlign.center,
                            color: AppColors.textColor,
                            fontSize: 18.0,
                          ).paddingOnly(bottom: Get.height),
                        ],
                      ).center(),
                    ).center();
                  }
                  return SizedBox(
                      width: 300, height: 300, child: Loader().center());
                }
              }),
              Obx(() => Visibility(
                  visible: (chatController.rooms.loading) &&
                      (chatController.rooms.result.data.isNotEmpty) &&
                      (chatController.connectionState.value !=
                          SocketConnectionState.error),
                  child: Loader().center())),
              Obx(() {
                return Visibility(
                  visible: chatController.connectionState.value ==
                      SocketConnectionState.error,
                  child: SizedBox(
                    height: Get.height * 2,
                  ),
                );
              })
            ],
          ).paddingSymmetric(horizontal: 20),
        ),
      ),
    ).makeSafeArea();
  }
}
