import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:taafee_mobile/common/extensions/widget_extension.dart';
import 'package:taafee_mobile/common/widgets/text.dart';
import 'package:taafee_mobile/common/widgets/toast.dart';
import 'package:taafee_mobile/features/chat/business%20logic%20layer/chat_controller.dart';
import 'package:taafee_mobile/features/chat/presentation_layer/widgets/replying.dart';
import '../../../../common/const/const.dart';
import '../../../../core/utils/utils.dart';
import '../../data_layer/model/message.dart';

// ignore: must_be_immutable
class ChatFooterWidget extends StatelessWidget {
  final TextEditingController textController = TextEditingController();
  final ChatController chatController = Get.find<ChatController>();
  final FocusNode? focusNode;
  ChatFooterWidget({super.key, this.focusNode});
  GlobalKey<FormState> sendMessageFormKey = GlobalKey<FormState>();

  MessageModel messageModel = MessageModel.zero();

  @override
  Widget build(BuildContext context) {
    messageModel.user = chatController.chatUser;
    chatController.initRecorder();
    return Container(
      color: Colors.transparent,
      child: Column(
        children: [
          Obx(() {
            return Visibility(
                visible: chatController.isReplying.value,
                child: ReplyingWidget().paddingSymmetric(
                  horizontal: 10,
                ));
          }),
          SizedBox(
            height: 60,
            child: Container(
              color: Colors.white,
              padding: const EdgeInsets.symmetric(horizontal: 10),
              child: Row(
                children: [
                  Obx(() {
                    return Visibility(
                      visible: !chatController.isRecording.value,
                      child: Form(
                        key: sendMessageFormKey,
                        child: TextFormField(
                          onTap: () {
                            chatController.scrollControllerJump();
                          },
                          focusNode: focusNode,
                          onChanged: (value) {
                            chatController.scrollControllerJump();
                            messageModel.content = value;
                          },
                          validator: (value) {
                            if (value == null || value == '') {
                              return "message_can't_be_empty".tr;
                            }
                            return null;
                          },
                          textInputAction: TextInputAction.send,
                          cursorColor: AppColors.primeColor,
                          onFieldSubmitted: (value) async {
                            if (sendMessageFormKey.currentState!.validate()) {
                              messageModel.type = MessageType.text;
                              if (chatController.isReplying.value) {
                                messageModel.repliedMessage =
                                    chatController.replyModel.value;
                                chatController.toggleIsReplying();
                              } else {
                                messageModel.repliedMessage = null;
                              }
                              textController.clear();

                              await chatController.sendMessage(messageModel,
                                  onError: (err) {
                                Toast.showToast(
                                    'you_have_no_internet_connection'.tr);
                              });

                              chatController.scrollControllerJump();
                            }
                          },
                          textAlignVertical: TextAlignVertical.center,
                          keyboardType: TextInputType.multiline,
                          controller: textController,
                          decoration: InputDecoration(
                            filled: true,
                            fillColor: AppColors.backGroundColor,
                            enabledBorder: OutlineInputBorder(
                              borderSide: BorderSide(
                                  color: AppColors.backGroundColor, width: 0.5),
                              borderRadius: BorderRadius.circular(30),
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderSide: BorderSide(
                                  color: AppColors.backGroundColor, width: 0.5),
                              borderRadius: BorderRadius.circular(30),
                            ),
                            disabledBorder: OutlineInputBorder(
                              borderSide: BorderSide(
                                  color: AppColors.backGroundColor, width: 5),
                              borderRadius: BorderRadius.circular(30),
                            ),
                            border: OutlineInputBorder(
                              borderSide: BorderSide(
                                  color: AppColors.backGroundColor, width: 5),
                              borderRadius: BorderRadius.circular(30),
                            ),
                            contentPadding:
                                const EdgeInsets.symmetric(horizontal: 12),
                          ),
                        ).expanded(7),
                      ),
                    );
                  }),
                  Obx(() {
                    if (chatController.isRecording.value) {
                      return Center(
                              child: RegularTextWidget(
                                  chatController.recordingTime.value))
                          .expanded(7);
                    } else {
                      return Container();
                    }
                  }),
                  Obx(() {
                    if (chatController.isRecording.value) {
                      return const Icon(Icons.stop).onTap(() async {
                        if (chatController.isReplying.value) {
                          chatController.toggleIsReplying();
                        }
                        messageModel.repliedMessage = null;

                        chatController.toggleIsRecording();
                        await chatController.stopRecording(onError: (err) {
                          Toast.showToast('you_have_no_internet_connection'.tr);
                        });
                        chatController.scrollControllerJump();
                      }).expanded(1);
                    } else {
                      return const Icon(Icons.mic).onTap(() async {
                        if (chatController.isReplying.value) {
                          chatController.toggleIsReplying();
                        }
                        messageModel.repliedMessage = null;
                        chatController.toggleIsRecording();

                        await chatController.record();
                      }).expanded(1);
                    }
                  }),
                  Obx(() {
                    return Visibility(
                        visible: chatController.isRecording.value,
                        child: SvgPicture.asset('assets/icons/x.svg')
                            .onTap(() async {
                          chatController.toggleIsRecording();
                          await chatController.cancelRecording();
                          chatController.scrollControllerJump();
                        }));
                  }),
                  SvgPicture.asset("assets/icons/gallery.svg").onTap(() async {
                    if (chatController.isReplying.value) {
                      chatController.toggleIsReplying();
                    }
                    messageModel.repliedMessage = null;

                    File? pickedImage = await Utils.pickSingleImage(context);
                    if (pickedImage != null) {
                      messageModel.content = '';
                      messageModel.type = MessageType.image;
                      messageModel.temporaryFile = pickedImage;
                      if (messageModel.temporaryFile != null) {
                        await chatController.sendMessage(messageModel,
                            filePath: pickedImage.path, onError: (err) {
                          Toast.showToast('you_have_no_internet_connection'.tr);
                        });
                      }
                    }
                    chatController.scrollControllerJump();
                  }).expanded(1),
                  Obx(() {
                    return Visibility(
                      visible: !chatController.isRecording.value,
                      child: const Icon(
                        Icons.send,
                        color: Colors.black,
                      ).onTap(() async {
                        if (sendMessageFormKey.currentState!.validate()) {
                          messageModel.type = MessageType.text;
                          if (chatController.isReplying.value) {
                            messageModel.repliedMessage = MessageModel.copy(
                                chatController.replyModel.value);
                            chatController.toggleIsReplying();
                          } else {
                            messageModel.repliedMessage = null;
                          }
                          textController.clear();

                          await chatController.sendMessage(messageModel,
                              onError: (err) {
                            Toast.showToast(
                                'you_have_no_internet_connection'.tr);
                          });

                          chatController.scrollControllerJump();
                        }
                      }).expanded(1),
                    );
                  })
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
