import {useEffect, useMemo, useRef, useState} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import ButtonMinimal from "../button/minimal";
import ChatsHistory from "./sections/chats-history";
import {showWidget} from "../../../../helpers";
import WidgetRow from "./sections/widget/row";
import Tooltip from "../tooltip";
import {HEADER_SCALE} from "./_data";
import useScrollIsolation from "../../hooks/use-scroll-isolation";
import {IS_MOBILE_DEVICE} from "../../containers/single";

export default function Home({chatbot, close, newChat, chatSelected, sendMessage, size, chatScreen, setChatScreen, getChats, viewMode}) {
    const [isScaled, setIsScaled] = useState(false);
    const bodyRef = useRef(null);

    // Isolate scroll events from external scroll libraries
    useScrollIsolation(bodyRef);

    useEffect(() => {
        const container = bodyRef.current;
        if (!container) {
            return;
        }

        const handleScroll = () => {
            if (container.offsetHeight >= container.scrollHeight) {
                return;
            }
            const scrollTop = container.scrollTop;

            if (!isScaled && scrollTop >= HEADER_SCALE.scroll.breakpoint.scale) {
                setIsScaled(true);
            } else if (isScaled && scrollTop <= HEADER_SCALE.scroll.breakpoint.expand) {
                setIsScaled(false);
            }
        };

        container.addEventListener('scroll', handleScroll, {passive: true});

        return () => container.removeEventListener('scroll', handleScroll, {passive: true});
    }, [isScaled]);

    const widgets = useMemo(() => {
        if (chatbot.utility.widgets?.length) {
            return chatbot.utility.widgets.filter(widget =>
                widget.published
                && showWidget(widget.locations, {screen: 'home'})
            )
        }
        return [];
    }, [chatbot.utility.widgets]);

    const showCloseButton = viewMode !== 'wp-block';

    if (chatScreen !== 'home') {
        return null;
    }

    return (
        <div className='lbaic-intro'>
            <div className='lbaic-intro-header' style={{
                '--lbaic-intro-header-height': isScaled ? '148px' : '',
                '--lbaic-intro-header-in-padding-top': isScaled ? '0px' : '',
                '--lbaic-intro-header-in-padding-bottom': isScaled ? '16px' : '',
                '--lbaic-intro-header-title-fs': isScaled ? '21px' : '',
                '--lbaic-intro-header-title-lh': isScaled ? '22.5px' : '',
                '--lbaic-intro-header-subtitle-fs': isScaled ? '12px' : '',
                '--lbaic-intro-header-subtitle-lh': isScaled ? '18px' : '',
                '--lbaic-intro-header-subtitle-padding-top': isScaled ? '6px' : '',
            }}>
                <div className="lbaic-intro-header-inner">
                    <div className='lbaic-intro-header-in'>
                        <div className='lbaic-intro-title'>
                            <h1 className='lbaic-intro-title-in'
                                dangerouslySetInnerHTML={{__html: chatbot.utility.greeting_text}}/>
                        </div>
                        <div className='lbaic-intro-subtitle'>
                            <p className='lbaic-intro-subtitle-in'
                               dangerouslySetInnerHTML={{__html: chatbot.utility.greeting_tagline}}/>
                        </div>
                    </div>
                    <div className='lbaic-intro-header-action'>
                        <button className='lbaic-intro-header-action-in' onClick={newChat}>
                            <span className='lbaic-intro-header-action-label'>{__("New chat", 'limb-chatbot')}</span>
                        </button>
                    </div>
                </div>
                {!IS_MOBILE_DEVICE && (
                    <div className='lbaic-intro-header-size'>
                        <Tooltip title={__("Change size", 'limb-chatbot')} tooltipPosition='bottom'
                                 arrowPosition={showCloseButton ? 'center' : 'right'}>
                            <ButtonMinimal classes='lbaic-button-minimal-28' onClick={size.set}
                                           icon={`size-${size.get}`}/>
                        </Tooltip>
                    </div>
                )}
                {showCloseButton && (
                    <div className='lbaic-intro-header-close'>
                        <ButtonMinimal classes='lbaic-button-minimal-28' onClick={() => close(chatbot.uuid)}
                                       icon='close'/>
                    </div>
                )}
            </div>
            <div ref={bodyRef} className={`lbaic-intro-main`}>
                <div className='lbaic-intro-body'>
                    <div className='lbaic-intro-body-in'>
                        {widgets.length > 0 && (
                            <div className='lbaic-intro-widgets show-widgets'>
                                {widgets.map(widget => (
                                    widget.type === 'chat_history' ? (
                                        <ChatsHistory
                                            key={widget.id}
                                            title={widget.title}
                                            getChats={getChats}
                                            chatSelected={chatSelected}
                                            setChatScreen={setChatScreen}
                                        />
                                    ) : (
                                        <WidgetRow
                                            key={widget.id}
                                            widgetRow={widget}
                                            sendMessage={sendMessage}
                                        />
                                    )
                                ))}
                            </div>
                        )}
                    </div>
                </div>
            </div>
            <div className='lbaic-intro-footer'>
                <div className='lbaic-intro-footer-in'>
                    <button className={`lbaic-intro-tab${chatScreen === 'home' ? ' active' : ''}`} onClick={() => setChatScreen('home')}>
                        <svg className='lbaic-intro-tab-i' xmlns='http://www.w3.org/2000/svg' fill='none'
                             viewBox='0 0 24 24'>
                            <use href='#lbaic-intro-home'/>
                        </svg>
                        <span className='lbaic-intro-tab-label'>{__("Home", 'limb-chatbot')}</span>
                    </button>
                    <button className={`lbaic-intro-tab${chatScreen === 'chat' ? ' active' : ''}`} onClick={() => setChatScreen('chat')}>
                        <svg className='lbaic-intro-tab-i' xmlns='http://www.w3.org/2000/svg' fill='none'
                             viewBox='0 0 24 24'>
                            <use href='#lbaic-intro-chats'/>
                        </svg>
                        <span className='lbaic-intro-tab-label'>{__("Chat", 'limb-chatbot')}</span>
                    </button>
                </div>
            </div>
        </div>
    )
}