import { useEffect, useRef } from 'react';

import {
  Chip,
  Toolbar,
} from 'konsta/react';
import { observer } from 'mobx-react';

import { rpc } from '../../../api/request';
import { ShmChannelMessageType } from '../../../api/types';
import pattern from '../../../pattern.jpg';
import store from '../../../stores/store';
import { channelStore } from '../../../stores/channelStore';
import MessageItem from './MessageItem';
import MessagePinnedItem from './MessagePinnedItem';
import MessagePopover, { MessagePopoverRefProps } from './MessagePopover';

const MessagesBlock = observer(() => {
    const pageRef = useRef<HTMLDivElement | null>(null);
    const messagePopoverRef = useRef<MessagePopoverRefProps | null>(null);

    const scrollToBottom = () => {
        setTimeout(() => {
            if (pageRef.current) {
                pageRef.current.scrollTop = pageRef.current.scrollHeight;
            }
        }, 100);
    };

    useEffect(() => {
        if (channelStore.channel?._id) {
            channelStore.loadMessages();
            if (!channelStore.channel?.closed) {
                channelStore.startMessagesPolling(scrollToBottom);
            } else {
                channelStore.stopMessagesPolling();
            }
        }
        return () => channelStore.stopMessagesPolling();
    }, [channelStore.channel?._id, channelStore.channel?.closed]);

    useEffect(() => {
        if (channelStore.messagesList?.length && pageRef.current) {
            scrollToBottom();
        }
    }, [channelStore.messagesList?.length]);

    const scrollByMessage = (_id: string | undefined) => {

        if (!_id) {
            console.warn("Не указан ID сообщения для скрола");
            return;
        }


        //Находим по #msg-<id> элемент и скроллим к нему в pageRef
        const element = document.getElementById(`msg-${_id}`);

        let offsetTop = element?.parentElement?.parentElement?.parentElement?.parentElement?.offsetTop;
        if (offsetTop && pageRef.current) {
            setTimeout(() => {
                if (offsetTop && pageRef.current) {
                    pageRef.current.scrollTo({
                        top: offsetTop - 100, // немного выше, чтобы не было внизу экрана
                        behavior: 'smooth',

                    });
                }
            }, 100);
        } else {
            console.warn(`Не найден элемент с ID msg-${_id}`);
        }


    }

    return <>

        {!!channelStore.pinnedMessage && <Toolbar top>

            <MessagePinnedItem
                onPin={() => {

                    rpc.pinnedMessage({
                        message: channelStore.pinnedMessage!._id,
                    }).then(() => {

                        channelStore.loadMessages();
                    });

                }}
                onClick={() => {
                    scrollByMessage(channelStore.pinnedMessage!._id);

                }}
                msg={channelStore.pinnedMessage}
            />


        </Toolbar>}
        <div ref={pageRef} className="overflow-y-scroll h-screen ">

            <div
                className='absolute top-0 left-0 w-full h-full bg-cover bg-center opacity-20'
                style={{
                    background: `url(${pattern})`
                }}
            >


            </div>
            <div className="flex flex-col relative z-1 px-4 mb-48">


                {channelStore.messagesList?.map((msg) => {
                    return (

                        <MessageItem
                            onReplayClick={(msg) => {
                                scrollByMessage(msg._id);
                            }}
                            onClick={() => {

                                messagePopoverRef.current?.open({
                                    msg: msg,

                                    onChange: () => {
                                        channelStore.loadMessages();
                                    },
                                    onPinned: () => {
                                        rpc.pinnedMessage({
                                            message: msg._id,
                                        }).then(() => {
                                            channelStore.loadMessages();
                                        });
                                    },
                                    onDelete: () => {
                                        rpc.channelDeleteMessage({
                                            message: msg._id,
                                            channel: channelStore.channel?._id,
                                        }).then(() => {
                                            channelStore.loadMessages();
                                        });
                                    },
                                    onReply: (msg) => {
                                        channelStore.setReplyMsg(msg);
                                    }

                                });


                            }}
                            onChange={() => {
                                channelStore.loadMessages();
                            }}
                            key={msg._id} msg={msg} />
                    );
                })}


                {!channelStore.channel?.closed && channelStore.channel?.type == "support" && channelStore.channel?.members?.find((member) => member.owner == store.userID) && <div

                    onClick={() => {
                        rpc.channelClose({
                            channel: channelStore.channel?._id,
                        }).then(() => {
                            channelStore.loadMessages();
                            channelStore.refreshChannel();
                        });
                    }}
                    className='flex justify-center items-center cursor-pointer active:opacity-50'>
                    <Chip>Закрыть обращение</Chip>
                </div>}

            </div>

            <MessagePopover


                ref={messagePopoverRef}
            />


        </div>
    </>


});

export default MessagesBlock;
