import 'package:fl_ks_smart_society_user/localization/localization_const.dart';
import 'package:fl_ks_smart_society_user/theme/theme.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class ChatScreen extends StatefulWidget {
  const ChatScreen({super.key});

  @override
  State<ChatScreen> createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  final messageList = [
    {
      "message": "Hello, Good morning! How are you?",
      "time": "9:30 PM",
      "isMe": false
    },
    {"message": "Hello, Goodmorning", "time": "9:35 PM", "isMe": true},
    {
      "message": "Lorem ipsum dolor sit amet consectetur. ",
      "time": "9:45 PM",
      "isMe": false
    },
    {"image": "assets/chat/image-1.png", "time": "10:11 AM", "isMe": true},
    {
      "message": "Lorem ipsum dolor sit amet consectetur. ",
      "time": "9:45 PM",
      "isMe": false
    },
    {
      "message": "Lorem ipsum dolor sit amet consectetur. ",
      "time": "9:35 PM",
      "isMe": true
    },
  ];

  TextEditingController messageController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.sizeOf(context);

    Map? data = ModalRoute.of(context)?.settings.arguments as Map?;

    final otherUserImage = data?['image'] ?? "assets/members/member-8.png";

    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        backgroundColor: whiteColor,
        centerTitle: false,
        titleSpacing: 0.0,
        toolbarHeight: 58.0,
        leading: IconButton(
          onPressed: () {
            Navigator.pop(context);
          },
          icon: const Icon(
            Icons.arrow_back,
            color: blackColor,
          ),
        ),
        title: headerTitle(otherUserImage, data),
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              physics: const BouncingScrollPhysics(),
              padding: const EdgeInsets.only(
                  top: fixPadding,
                  left: fixPadding * 2.0,
                  right: fixPadding * 2.0,
                  bottom: fixPadding),
              reverse: true,
              itemCount: messageList.length,
              itemBuilder: (context, index) {
                int reverseIndex = messageList.length - index - 1;
                return messageList[reverseIndex]['isMe'] == true
                    ? sendMessages(reverseIndex, size)
                    : receiveMessages(reverseIndex, otherUserImage);
              },
            ),
          ),
          messageField(),
        ],
      ),
    );
  }

  messageField() {
    return Container(
      margin: const EdgeInsets.only(
          left: fixPadding * 2.0,
          right: fixPadding * 2.0,
          bottom: fixPadding * 2.0),
      decoration: BoxDecoration(
        color: whiteColor,
        borderRadius: BorderRadius.circular(10.0),
        border: Border.all(color: primaryColor),
        boxShadow: [
          BoxShadow(
            color: primaryColor.withOpacity(0.2),
            blurRadius: 6.0,
          )
        ],
      ),
      alignment: Alignment.center,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Expanded(
            child: TextField(
              controller: messageController,
              cursorColor: primaryColor,
              style: regular15Primary,
              decoration: InputDecoration(
                border: InputBorder.none,
                contentPadding:
                    const EdgeInsets.symmetric(vertical: fixPadding * 1.5),
                prefixIcon: const Icon(
                  CupertinoIcons.camera,
                  color: primaryColor,
                  size: 20.0,
                ),
                hintText: tr(context, 'chat.write_message'),
                hintStyle: regular15Primary,
              ),
            ),
          ),
          sendButton()
        ],
      ),
    );
  }

  sendButton() {
    return SizedBox(
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: fixPadding),
        child: GestureDetector(
          onTap: () {
            if (messageController.text.isNotEmpty) {
              setState(() {
                messageList.add({
                  "message": messageController.text,
                  "time": DateFormat.jm().format(DateTime.now()),
                  "isMe": true
                });
                messageController.clear();
                messageList;
              });
            }
          },
          child: const Icon(
            Icons.send,
            color: primaryColor,
            size: 28.0,
          ),
        ),
      ),
    );
  }

  receiveMessages(int index, String image) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: fixPadding),
      child: Row(
        mainAxisAlignment: languageValue == 4
            ? MainAxisAlignment.end
            : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Column(
            mainAxisAlignment: languageValue == 4
                ? MainAxisAlignment.start
                : MainAxisAlignment.end,
            children: [
              Container(
                height: 25,
                width: 25,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  image: DecorationImage(
                    image: AssetImage(image),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              heightSpace,
              heightSpace,
            ],
          ),
          width5Space,
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  padding: const EdgeInsets.symmetric(
                      horizontal: fixPadding, vertical: fixPadding * 1.4),
                  margin: languageValue == 4
                      ? const EdgeInsets.only(left: fixPadding * 8.0)
                      : const EdgeInsets.only(right: fixPadding * 8.0),
                  decoration: BoxDecoration(
                    color: whiteColor,
                    borderRadius: languageValue == 4
                        ? const BorderRadius.only(
                            topLeft: Radius.circular(10.0),
                            topRight: Radius.circular(10.0),
                            bottomLeft: Radius.circular(10.0),
                          )
                        : const BorderRadius.only(
                            topLeft: Radius.circular(10.0),
                            topRight: Radius.circular(10.0),
                            bottomRight: Radius.circular(10.0),
                          ),
                    boxShadow: boxShadow2,
                  ),
                  child: Text(
                    messageList[index]['message'].toString(),
                    style: regular15Black,
                  ),
                ),
                heightBox(3.0),
                Text(
                  messageList[index]['time'].toString(),
                  style: regular12Grey,
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

  sendMessages(int index, Size size) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: fixPadding),
      child: Row(
        mainAxisAlignment: languageValue == 4
            ? MainAxisAlignment.start
            : MainAxisAlignment.end,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                messageList[index]['message'] != null
                    ? Container(
                        padding: const EdgeInsets.symmetric(
                            horizontal: fixPadding, vertical: fixPadding * 1.4),
                        margin: languageValue == 4
                            ? const EdgeInsets.only(right: fixPadding * 8.0)
                            : const EdgeInsets.only(left: fixPadding * 8.0),
                        decoration: BoxDecoration(
                          color: primaryColor,
                          boxShadow: buttonShadow,
                          borderRadius: languageValue == 4
                              ? const BorderRadius.only(
                                  topLeft: Radius.circular(10.0),
                                  topRight: Radius.circular(10.0),
                                  bottomRight: Radius.circular(10.0),
                                )
                              : const BorderRadius.only(
                                  topLeft: Radius.circular(10.0),
                                  topRight: Radius.circular(10.0),
                                  bottomLeft: Radius.circular(10.0),
                                ),
                        ),
                        child: Text(
                          messageList[index]['message'].toString(),
                          style: regular15White,
                        ),
                      )
                    : Container(
                        height: 96,
                        width: size.width * 0.4,
                        margin: languageValue == 4
                            ? const EdgeInsets.only(right: fixPadding * 8.0)
                            : const EdgeInsets.only(left: fixPadding * 8.0),
                        decoration: BoxDecoration(
                          borderRadius: languageValue == 4
                              ? const BorderRadius.only(
                                  topLeft: Radius.circular(10.0),
                                  topRight: Radius.circular(10.0),
                                  bottomRight: Radius.circular(10.0),
                                )
                              : const BorderRadius.only(
                                  topLeft: Radius.circular(10.0),
                                  topRight: Radius.circular(10.0),
                                  bottomLeft: Radius.circular(10.0),
                                ),
                          boxShadow: buttonShadow,
                          image: DecorationImage(
                            image: AssetImage(
                              messageList[index]['image'].toString(),
                            ),
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                heightBox(3.0),
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      messageList[index]['time'].toString(),
                      style: regular12Grey,
                    ),
                    widthBox(fixPadding * 0.3),
                    const Icon(
                      Icons.done_all,
                      color: primaryColor,
                      size: 15.0,
                    )
                  ],
                ),
              ],
            ),
          ),
          width5Space,
          Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Container(
                height: 25,
                width: 25,
                decoration: const BoxDecoration(
                  shape: BoxShape.circle,
                  image: DecorationImage(
                    image: AssetImage("assets/profile/user-image.png"),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              heightSpace,
              heightSpace,
            ],
          )
        ],
      ),
    );
  }

  headerTitle(String otherUserImage, Map<dynamic, dynamic>? data) {
    return Row(
      children: [
        FittedBox(
          child: Container(
            height: 40.0,
            width: 40.0,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              image: DecorationImage(
                image: AssetImage(otherUserImage),
              ),
            ),
          ),
        ),
        widthSpace,
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                data?['name'] ?? "Cameron Williamson",
                style: regular16Black,
                overflow: TextOverflow.ellipsis,
              ),
              heightBox(fixPadding * 0.3),
              const Text(
                "B 102",
                style: regular15Grey,
                overflow: TextOverflow.ellipsis,
              )
            ],
          ),
        )
      ],
    );
  }
}
