import {useCallback, useState, useEffect} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import {GetChatMessages} from "../../../../../../../../../rest/chats";
import {handleError} from "../../../../../../../../../helpers/notifications";
import Body from "./components/body";
import Footer from "./components/footer";

const MESSAGES_DEFAULT_PARAMS = {
    perPage: 10,
    orderBy: 'id',
    order: 'desc',
};

const ChatConversation = ({chat, setDetailsOpen, loading, setLoading, notifications}) => {
    const [messages, setMessages] = useState([]);
    const [messagesPagination, setMessagesPagination] = useState({
        page: 1,
        per_page: MESSAGES_DEFAULT_PARAMS.perPage,
        total: 0,
    });
    const [messagesParams, setMessagesParams] = useState({
        orderby: MESSAGES_DEFAULT_PARAMS.orderBy,
        order: MESSAGES_DEFAULT_PARAMS.order,
    });
    const [isMessagesFetched, setIsMessagesFetched] = useState(false);

    const hasMoreMessages = messagesPagination.page * messagesPagination.per_page < messagesPagination.total;

    useEffect(() => {
        // Reset messages fetched state
        setIsMessagesFetched(false);

        if (chat?.uuid) {
            fetchMessages(1, messagesPagination.perPage, {
                orderby: MESSAGES_DEFAULT_PARAMS.orderBy,
                order: MESSAGES_DEFAULT_PARAMS.order,
            }, true);
        } else {
            setMessages([]);
            setIsMessagesFetched(true);
        }
    }, [chat?.uuid]);

    /**
     * Fetch chat messages
     *
     * @param {number} page Page
     * @param {number} perPage Per page
     * @param {object} params Params
     * @param {boolean} reset Reset messages
     * @return {Promise<void>}
     */
    const fetchMessages = useCallback(async (page, perPage, params = {}, reset = false) => {
        setLoading(prev => prev + 1);
        try {
            const reqParams = {
                page: page || 1,
                per_page: perPage || MESSAGES_DEFAULT_PARAMS.perPage,
                orderby: params.orderBy || MESSAGES_DEFAULT_PARAMS.orderBy,
                order: params.order || MESSAGES_DEFAULT_PARAMS.order,
                include: ['metas', 'dataset_entries', 'source_link', 'agent'],
            };
            // Get messages
            const res = await GetChatMessages(LimbChatbot.rest.url, LimbChatbot.rest.nonce, chat.uuid, reqParams);
            const newMessages = res.items?.length > 0 ? res.items.reverse() : [];
            // Update messages state
            if (reset) {
                setMessages(newMessages);
            } else {
                setMessages(prevState => [...newMessages, ...prevState])
            }
            // Update messages params
            setMessagesPagination(prevState => ({
                ...prevState,
                page: reqParams.page,
                total: res.total
            }));
            setMessagesParams(prevState => ({
                ...prevState,
                orderby: reqParams.orderby,
                order: reqParams.order,
            }));
        } catch (e) {
            handleError(e, notifications.set, {
                title: __('Failed to fetch chat messages.', 'limb-chatbot'),
                content: e.message ? __(e.message, 'limb-chatbot') : __('Please check and try again.', 'limb-chatbot'),
            });
        }
        setLoading(prev => prev - 1);
        setIsMessagesFetched(true);
    }, [chat?.uuid]);

    const loadMoreMessages = async () => {
        // Load more if has more
        if (hasMoreMessages) {
            await fetchMessages(messagesPagination.page + 1, messagesPagination.per_page, messagesParams);
        }
    }

    return (
        <div className="lbaic-settings-chats-content">
            <div className="lbaic-settings-chats-content-wrapper">
                <Body
                    chat={chat}
                    messages={messages}
                    loading={loading}
                    isFetched={isMessagesFetched}
                    hasMore={hasMoreMessages}
                    loadMore={loadMoreMessages}
                    setDetailsOpen={setDetailsOpen}
                    notifications={notifications}
                />
            </div>
            {/*<Footer/>*/}
        </div>
    );
};

export default ChatConversation;
