import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from 'react';

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

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

export type MessagesBlockRefProps = {
    loadMessages: () => void;
}

type MessagesBlockProps = {
    selectChannel: ShmChannelType | null,
    onReply: (msg: ShmChannelMessageType) => void;
    onChannelChange: () => void;
}

const UPDATE_MESSAGES_INTERVAL = 10000;

const MessagesBlock = forwardRef<MessagesBlockRefProps, MessagesBlockProps>(({ selectChannel, onReply, onChannelChange }, ref) => {

    const [messagesList, setMessagesList] = useState<ShmChannelMessageType[] | null>(null);
    const [pinnedMessage, setPinnedMessage] = useState<ShmChannelMessageType | null>(null);

    const refLastLoadMessage = useRef<ShmChannelMessageType | null>(null);

    const lashHash = useRef<string | null>(null);


    const pageRef = useRef<any>(null);


    const loadMessagesInterval = useRef<any>(null);

    useImperativeHandle(ref, () => ({
        loadMessages: () => {
            loadMessages();
        }
    }));


    useEffect(() => {
        if (selectChannel?._id) {
            loadMessagesInterval.current = setInterval(() => {
                loadMessages();
            }, UPDATE_MESSAGES_INTERVAL);
        }
        return () => {
            if (loadMessagesInterval.current) {
                clearInterval(loadMessagesInterval.current);
            }
        }
    }, [selectChannel?._id]);

    useEffect(() => {
        if (selectChannel?._id) {
            loadMessages();
        }
    }, [selectChannel?._id]);


    const scrollToBottom = () => {

        setTimeout(() => {
            /* pageRef.current.scrollTo({
                 top: pageRef.current.scrollHeight,
                 behavior: ''
 
             });*/

            // Скролл без анимации моментально вниз
            pageRef.current.scrollTop = pageRef.current.scrollHeight;
        }, 100);
    };

    const messagePopoverRef = useRef<MessagePopoverRefProps | null>(null);



    const loadMessages = () => {
        if (selectChannel?._id) {
            rpc.channelMessages({
                channel: selectChannel._id,
                limit: 50,
                offset: 0
            }, ["shmChannelMessages"]).then(({ result: json }) => {
                if (refLastLoadMessage.current) {
                    if (refLastLoadMessage.current._id != json?.data?.[json?.data.length - 1]?._id) {
                        scrollToBottom();
                    }

                    lashHash.current = json?.hash ?? null;

                } else {
                    scrollToBottom();
                }

                refLastLoadMessage.current = json?.data?.[json?.data.length - 1] ?? null;
                console.log(json);
                setMessagesList(json?.data ?? []);
            });
        }
    };

    useEffect(() => {


        let findPinnedList = messagesList?.filter((e) => e.pinned?.enabled);

        if (!findPinnedList) {
            return;
        }

        let findPinned = findPinnedList[findPinnedList?.length - 1] ?? null;

        if (findPinned?._id != pinnedMessage?._id) {
            setPinnedMessage(findPinned ?? null);
        }

    }, [messagesList])

    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) {
            setTimeout(() => {

                if (offsetTop) {

                    pageRef.current.scrollTo({
                        top: offsetTop - 100, // немного выше, чтобы не было внизу экрана
                        behavior: 'smooth',

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


    }

    return <>

        {!!pinnedMessage && <Toolbar top>

            <MessagePinnedItem
                onPin={() => {

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

                        loadMessages();
                    });

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

                }}
                msg={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">


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

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

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

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

                                });


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


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

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

            </div>

            <MessagePopover


                ref={messagePopoverRef}
            />


        </div>
    </>


});

export default observer(MessagesBlock);
