import 'dayjs/locale/ru'; // load on demand

import React, {
  useEffect,
  useRef,
  useState,
} from 'react';

import dayjs from 'dayjs';
import {
  Link,
  Navbar,
  Page,
  Toolbar,
} from 'konsta/react';
import { observer } from 'mobx-react';
import { MdClose } from 'react-icons/md';

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

dayjs.locale("ru");



const ChannelPage = ({ noPage }: {
    noPage?: boolean;
}) => {

    const { userID, channelList, loadChannelList, selectChannelID, setSelectChannelID } = store;

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

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

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

    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 [replayMsg, setReplyMsg] = useState<ShmChannelMessageType | null>(null);


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

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

    const loadMessages = () => {
        if (selectChannel?._id) {
            rpc.channelMessages({
                channel: selectChannel._id,
                limit: 50,
                offset: 0
            }, ["shmChannelMembers", "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 ?? []);
            });
        }
    };

    const interval = useRef<any>(null);

    const [selectChannel, setSelectChannel] = useState<ShmChannelType | null>(null);

    useEffect(() => {


        if (selectChannelID) {
            rpc.channelInfo({
                channel: selectChannelID,
            }).then(({ result: data }) => {
                if (data) {
                    setSelectChannel(data);
                }
            });
        }




    }, []);

    useEffect(() => {
        if (selectChannel) {

            loadMessages();

            interval.current = setInterval(() => {
                loadMessages();
            }, 5000);

            return () => {
                if (interval.current) {
                    clearInterval(interval.current);
                }

            };

        }
    }, [selectChannel]);


    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}`);
        }


    }

    const pageRef = useRef<any>(null);

    const scrollToBottom = () => {

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

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


    const PageWrapper = ({ children }: {
        children: React.ReactNode;
    }) => {

        if (noPage) {

            return <div
                className='relative w-full h-full'>{children}</div>;
        }

        return (
            <Page className="ios:bg-white ios:dark:bg-black overflow-hidden">
                {children}
            </Page>
        );


    }

    return (<PageWrapper>



        {!store.cap && <Navbar
            title={
                <div className="text-sm ml-3">{selectChannel?.name}</div>
            }
            right={
                <>
                    <Link
                        onClick={() => {
                            setSelectChannel(null);

                            loadChannelList();
                        }}

                    >

                        <MdClose size={24} />

                    </Link>

                </>
            }
        ></Navbar>}

        {!!pinnedMessage && <Toolbar top>

            <MessagePinnedItem
                onPin={() => {

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

                        loadMessages();
                    });

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

                }}
                msg={pinnedMessage}
            />


        </Toolbar>}

        <RichMessagebar
            removeReplay={() => {
                setReplyMsg(null);
            }}
            replayMsg={replayMsg}
            onSended={() => {
                loadMessages();
            }}

        />

        <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) => {
                                        setReplyMsg(msg);
                                    }

                                });


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



            </div>
        </div>

        <MessagePopover


            ref={messagePopoverRef}
        />

    </PageWrapper>

    );
};

export default observer(ChannelPage);
