import {useEffect, useRef, useState} from '@wordpress/element';
import {__} from "@wordpress/i18n";
import ButtonInput from '../button/input';
import ButtonSend from '../button/send';
import {loadTheFile} from "../../includes/helpers";
import Tooltip from "../tooltip";
import {prepareUserMessage} from "../../../../helpers";
import {createHooks} from "@wordpress/hooks";
import MessageInput, {validateInput} from "./message-input";
import ButtonSkip from "../button/skip";
import Typing from "../body/messages/message/type/typing";
import {useConfirm} from "../confirm";
import LeadCapture from "./lead-capture";

if (!LimbChatbot.Hooks) {
    LimbChatbot.Hooks = createHooks();
}

export default function Footer({
                                   chatbot,
                                   chatScreen,
                                   send,
                                   isChatRunning,
                                   isChatStreaming,
                                   isChatStreamTyping,
                                   isPreviewSaving,
                                   lastMessageParameter,
                                   viewMode,
                                   isLiveAgentMode,
                                   isInPreviewMode,
                                   shouldShowLiveAgentTyping,
                                   chatbotUtility,
                                   leadCaptureWidget,
                                   setShowLeadCaptureWidget,
                                   sendMessageAfterLeadCaptureRef,
                                   isWidgetsLoading
                               }) {
    // Data
    const [text, setText] = useState('');
    const [images, setImages] = useState([]);
    const [files, setFiles] = useState([]);
    const [voice, setVoice] = useState(null);
    // States
    const [textareaHeight, setTextareaHeight] = useState(50);
    const [canSendMessage, setCanSendMessage] = useState(false);
    const [isSavingPreviewSettings, setIsSavingPreviewSettings] = useState(false);
    const [isInputValid, setIsInputValid] = useState(true);
    const [isEndingSession, setIsEndingSession] = useState(false);
    // Elements refs
    const inputActionsRef = useRef(null);
    const textareaRef = useRef(null);
    const imageInputRef = useRef(null);
    // Confirm dialog
    const confirm = useConfirm();

    // Is in process
    const isInProcess = isChatRunning || isChatStreaming || isChatStreamTyping || isPreviewSaving;
    // Input type - handle both "vector_search" (backend) and "recommendation" (frontend)
    const inputType = lastMessageParameter?.type === 'vector_search' ? 'recommendation' : lastMessageParameter?.type;

    // Autofocus footer input whenever we're showing the chat input (not lead capture):
    // after lead capture submit, when parameter config changes, or when entering chat screen.
    useEffect(() => {
        const showChatInput = chatScreen === 'chat' && !leadCaptureWidget;
        if (!showChatInput || isInProcess) {
            return;
        }
        const isMobile = window.innerWidth < 768;
        if (isMobile || viewMode === 'wp-block') {
            return;
        }
        // RecommendationInput uses its own search field; it handles autofocus internally.
        if (inputType === 'recommendation') {
            return;
        }
        const frameId = requestAnimationFrame(() => {
            textareaRef.current?.focus();
        });
        return () => cancelAnimationFrame(frameId);
    }, [chatScreen, leadCaptureWidget, isInProcess, viewMode, lastMessageParameter, inputType]);

    // Validate input based on input type
    useEffect(() => {
        setIsInputValid(validateInput(text, inputType));
    }, [text, inputType]);

    useEffect(() => {
        setCanSendMessage(
            (
                (text.trim().length > 0 && isInputValid)
                || images.length > 0
                || files.length > 0
                || voice
            ) && !isInProcess && !isWidgetsLoading);
    }, [text, images, files, voice, isInProcess, isInputValid, isWidgetsLoading]);

    useEffect(() => {
        LimbChatbot.Hooks.addAction(
            'preview_settings_on_saving_process',
            'lbaic/admin/page/settings/preview/save',
            setIsSavingPreviewSettings
        );

        return () => {
            LimbChatbot.Hooks.removeAction(
                'preview_settings_on_saving_process',
                'lbaic/admin/page/settings/preview/save'
            );
        };
    }, []);

    /**
     * Keep text message state
     *
     * @param {Event} e Event
     */
    const onTextChange = (e) => {
        setText(e.target.value);
        // Adjust the textarea height
        setTextareaHeight(e.target.value ? textareaRef.current.scrollHeight : 50);
    }

    /**
     * Send message on Enter button click
     *
     * @param {Event} e Event
     */
    const handleKeyDown = (e) => {
        if (e.key === 'Enter' && !e.shiftKey && !isInProcess && !isWidgetsLoading) {
            e.preventDefault();
            sendMessage();
        }
    }

    /**
     * Handle uploaded images
     */
    const attacheImages = (e) => {
        if (e.target.files?.length) {
            Array.from(e.target.files).forEach((file) => loadTheFile(file).then(image => {
                setImages(prevState => [...prevState, image]);
            }).catch(e => {
                console.error(e);
            }));
        }
    }

    /**
     * Send message
     */
    const sendMessage = () => {
        if (canSendMessage) {
            // Send the message
            send(prepareUserMessage({
                text,
                images,
                files,
                voice
            }));
            // Reset state
            setText('');
            setImages([]);
            setFiles([]);
            setVoice(null);
            // Reset textarea height
            setTextareaHeight(50);
        }
    }

    /**
     * Handle button click
     *
     * @param {string} label Button label
     * @param {string} value Button value
     */
    const handleButtonClick = (label, value) => {
        if (!isInProcess) {
            // For button-type parameters, send both text and parameter_value
            // Format matches user requirement: text as string, parameter_value as string
            send({
                role: 'user',
                content: [
                    {
                        type: 'text',
                        text: {
                            value: label
                        }
                    },
                    {
                        type: 'parameter_value',
                        parameter_value: {
                            value: value
                        }
                    }
                ]
            });
        }
    }

    /**
     * Handle action cancellation
     */
    const handleCancelAction = () => {
        // Send action cancellation message
        send({
            role: "user",
            content: [
                {
                    type: "action_cancellation",
                }
            ]
        });
    }

    /**
     * Skip parameter (send an empty message)
     */
    const skipParameter = () => {
        // Send an empty message for optional parameter
        send(prepareUserMessage({
            text: '',
            images: [],
            files: [],
            voice: null
        }));
    }

    /**
     * Handle end session button click
     */
    const handleEndSession = async () => {
        // Prevent multiple clicks
        if (isEndingSession) {
            return;
        }

        const confirmed = await confirm(__("Are you sure you want to end the session?", 'limb-chatbot'));
        if (confirmed) {
            // Disable button to prevent duplicate requests
            setIsEndingSession(true);
            try {
                await send({
                    role: "user",
                    content: [
                        {
                            type: "live_agent_disconnection"
                        }
                    ]
                });
            } catch (e) {
                // If send fails, re-enable button so user can try again
                setIsEndingSession(false);
            }
            // Note: If successful, isLiveAgentMode will become false and button will be hidden
            // If failed and still in live agent mode, button is re-enabled above
        }
    }

    if (chatScreen === 'chat-history') {
        return null;
    }

    return (
        <div className='lbaic-footer' style={{
            '--lbaic-input-pie': inputActionsRef.current ? `${inputActionsRef.current?.clientWidth + 13}px` : undefined,
            '--lbaic-textarea-height': `${textareaHeight}px`
        }}>
            {leadCaptureWidget && chatScreen === 'chat' ? (
                <LeadCapture
                    widget={leadCaptureWidget}
                    sendUserMessage={send}
                    userMessageArgsRef={sendMessageAfterLeadCaptureRef}
                    setShowLeadCaptureWidget={setShowLeadCaptureWidget}
                    chatbotUtility={chatbotUtility}
                    isInPreviewMode={isInPreviewMode}
                />
            ) : (
                <>
                    {isChatRunning && <Typing/>}
                    {shouldShowLiveAgentTyping && <Typing label={__("Responding...", 'limb-chatbot')}/>}
                    {chatScreen === 'chat' &&
                        <>
                            {isLiveAgentMode && (
                                <div className="lbaic-agent-off">
                                    <button
                                        className="lbaic-agent-off-in"
                                        onClick={handleEndSession}
                                        disabled={isEndingSession}
                                    >
                                        <span className='lbaic-agent-off-button-in'>
                                            <svg className='lbaic-agent-off-button-i' xmlns='http://www.w3.org/2000/svg'>
                                                <use href='#lbaic-cancel'/>
                                            </svg>
                                        </span>
                                        <span className='lbaic-agent-off-label'>{__("End live session", 'limb-chatbot')}</span>
                                    </button>
                                </div>
                            )}
                            {lastMessageParameter ? (
                                inputType === 'recommendation' ? (
                                    <MessageInput
                                        textareaRef={textareaRef}
                                        text={text}
                                        onTextChange={onTextChange}
                                        onKeyDown={handleKeyDown}
                                        inputType={inputType}
                                        placeholder={lastMessageParameter.placeholder || chatbot.utility.message_placeholder}
                                        isValid={isInputValid}
                                        config={lastMessageParameter.config}
                                        parameter={lastMessageParameter}
                                        onButtonClick={handleButtonClick}
                                        onCancelAction={handleCancelAction}
                                        send={send}
                                        chatbotUtility={chatbotUtility}
                                        isInProcess={isInProcess}
                                        isSavingPreviewSettings={isSavingPreviewSettings}
                                        sendDisabled={isInProcess || !canSendMessage || isSavingPreviewSettings || isWidgetsLoading}
                                        sendLabel={chatbot.utility.send_button_text}
                                        parameterLabel={lastMessageParameter.label}
                                    />
                                ) : (
                                    <div className='lbaic-input-container'>
                                        <div className='lbaic-input-action-container'>
                                            <p className='lbaic-input-action-label'>{lastMessageParameter.label}</p>
                                            <button className='lbaic-input-action-button' onClick={handleCancelAction}>
                                                <svg className='lbaic-input-action-button-i' xmlns='http://www.w3.org/2000/svg'>
                                                    <use href='#lbaic-cancel'/>
                                                </svg>
                                                {__("Cancel", 'limb-chatbot')}
                                            </button>
                                        </div>
                                        <div className='lbaic-input-holder'>
                                            <div
                                                className={`lbaic-input-holder-in${inputType === 'buttons' ? ' no-background' : ''}`}>
                                                <div className='lbaic-input-holder-inner'>
                                                    <MessageInput
                                                        textareaRef={textareaRef}
                                                        text={text}
                                                        onTextChange={onTextChange}
                                                        onKeyDown={handleKeyDown}
                                                        inputType={inputType}
                                                        placeholder={lastMessageParameter.placeholder || chatbot.utility.message_placeholder}
                                                        isValid={isInputValid}
                                                        config={lastMessageParameter.config}
                                                        onButtonClick={handleButtonClick}
                                                        onCancelAction={handleCancelAction}
                                                        onSkipAction={!lastMessageParameter?.required ? skipParameter : undefined}
                                                        skipDisabled={isInProcess || isSavingPreviewSettings}
                                                        skipLabel={__("Skip", 'limb-chatbot')}
                                                        isInProcess={isInProcess}
                                                        isSavingPreviewSettings={isSavingPreviewSettings}
                                                        sendDisabled={isInProcess || !canSendMessage || isSavingPreviewSettings || isWidgetsLoading}
                                                        sendLabel={chatbot.utility.send_button_text}
                                                        parameterLabel={lastMessageParameter.label}
                                                    />
                                                </div>
                                                {inputType !== 'buttons' && (
                                                    <div className='lbaic-input-actions' ref={inputActionsRef}>
                                                        {!lastMessageParameter?.required && (
                                                            <div className='lbaic-input-actions-in'>
                                                                <ButtonSkip
                                                                    onClick={skipParameter}
                                                                    label={__("Skip", 'limb-chatbot')}
                                                                    disabled={isInProcess || isSavingPreviewSettings}/>
                                                            </div>
                                                        )}
                                                        <div className='lbaic-input-actions-in'>
                                                            <ButtonSend
                                                                onClick={sendMessage}
                                                                icon='send'
                                                                label={chatbot.utility.send_button_text}
                                                                disabled={isInProcess || !canSendMessage || isSavingPreviewSettings || isWidgetsLoading}/>
                                                        </div>
                                                    </div>
                                                )}
                                            </div>
                                        </div>
                                    </div>
                                )
                            ) : (
                                <div className='lbaic-input-holder'>
                                    <div className='lbaic-input-holder-in'>
                                        {images.length > 0 && <div className='lbaic-upload-container'>
                                            {images.map((file, index) => {
                                                return (<div key={`image-${index}`} className='lbaic-upload-in'>
                                                    <img className='lbaic-upload-file' src={file.base64} alt={file.name}/>
                                                    <button className='lbaic-upload-remove'
                                                            onClick={() => setImages(prevState => prevState.filter((item, i) => i !== index))}>
                                                        <svg className='lbaic-upload-remove-i'
                                                             xmlns='http://www.w3.org/2000/svg'
                                                             viewBox='0 0 24 24'>
                                                            <use href='#lbaic-close'/>
                                                        </svg>
                                                    </button>
                                                </div>)
                                            })}
                                        </div>}
                                        <div className='lbaic-input-holder-inner'>
                                            <MessageInput
                                                textareaRef={textareaRef}
                                                text={text}
                                                onTextChange={onTextChange}
                                                onKeyDown={handleKeyDown}
                                                inputType={inputType}
                                                placeholder={chatbot.utility.message_placeholder}
                                                isValid={isInputValid}
                                            />
                                        </div>
                                        <div className='lbaic-input-actions' ref={inputActionsRef}>
                                            {chatbot.utility.image &&
                                                <div className='lbaic-input-actions-in'>
                                                    <Tooltip tooltipPosition='top'
                                                             title={__("Attache image(s)", 'limb-chatbot')}>
                                                        <ButtonInput
                                                            onClick={() => imageInputRef.current.click()}
                                                            icon='image'/>
                                                    </Tooltip>
                                                    <input
                                                        ref={imageInputRef}
                                                        type="file"
                                                        accept="image/*"
                                                        style={{display: 'none'}}
                                                        onChange={attacheImages}
                                                        multiple={chatbot.utility.multiple_images}
                                                    />
                                                </div>}
                                            {chatbot.utility.voice &&
                                                <div className='lbaic-input-actions-in'>
                                                    <Tooltip tooltipPosition='top' arrowPosition='right'
                                                             title={__("Use microphone to send voice message", 'limb-chatbot')}>
                                                        <ButtonInput
                                                            onClick={() => {
                                                            }}
                                                            icon='microphone'/>
                                                    </Tooltip>
                                                </div>}
                                            <div className='lbaic-input-actions-in'>
                                                <ButtonSend
                                                    onClick={sendMessage}
                                                    icon='send'
                                                    label={chatbot.utility.send_button_text}
                                                    disabled={isInProcess || !canSendMessage || isSavingPreviewSettings || isWidgetsLoading}/>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            )}
                        </>
                    }
                </>
            )}
        </div>
    )
}