import {useState} from "@wordpress/element";
import {__, sprintf} from "@wordpress/i18n";
import {
    getBase64FormatedSize,
    getSmartFormatedDate,
    isImage,
    prepareChatbotMessage
} from "../../../../../../../../../../../../helpers";
import MessageSourcesPopup from "../../../popups/message-sources";
import Badge from "../../../../../../../../../../fields/badge";

// Content types that can be rendered in the admin view
const RENDER_CONTENT_TYPES = ['text', 'attachment', 'audio', 'action_submission'];

// Agent status content types
const AGENT_JOINED_TYPE = 'slack_connection';
const AGENT_LEFT_TYPE = 'live_agent_disconnection';

export default function Message({
                                    message,
                                    messageIndex,
                                    userInfo,
                                    isNewRole,
                                    setDetailsOpen,
                                    notifications,
                                    joinedAgent,
                                    leftAgent
                                }) {
    const [showSourcesPopup, setShowSourcesPopup] = useState(false);

    // Check if message has any renderable content types
    // Don't render messages that don't have renderable content
    // (e.g., messages with only action_cancellation or parameter types)
    const hasRenderableContent = message.content?.length > 0 && message.content.some(item => RENDER_CONTENT_TYPES.includes(item.type));
    if (!hasRenderableContent) {
        return null;
    }

    const handleUserClick = () => {
        if (message.role === 'user') {
            setDetailsOpen(true);
        }
    }

    // Sender name
    let sender = {
        name: __("Unknown", "limb-chatbot"),
        icon: <span className='lbaic-settings-chats-avatar-off'>?</span>,
        iconIsImage: false
    };
    switch (message.role) {
        case 'user':
            sender.name = userInfo?.name;
            sender.icon = <span className='lbaic-settings-chats-avatar-off'>{userInfo?.letters}</span>;
            break;
        case 'assistant':
            // Check if message has an agent (live agent)
            if (message.agent) {
                sender.name = message.agent.name || __('Live Agent', 'limb-chatbot');
                // Use smallest avatar (24px)
                const avatarUrl = message.agent.avatar_urls?.['24'] || message.agent.avatar_urls?.['48'] || message.agent.avatar_urls?.['96'];
                if (avatarUrl) {
                    sender.icon = (
                        <img
                            className='lbaic-settings-chats-avatar-pic'
                            src={avatarUrl}
                            alt={message.agent.name || ''}
                        />
                    );
                    sender.iconIsImage = true;
                } else {
                    // Fallback to first letter of agent name
                    const agentLetter = message.agent.name ? message.agent.name.charAt(0).toUpperCase() : 'A';
                    sender.icon = <span className='lbaic-settings-chats-avatar-off'>{agentLetter}</span>;
                }
            } else {
                sender.name = __('AI Assistant', 'limb-chatbot');
                sender.icon = (
                    <svg className='lbaic-settings-chats-avatar-i' xmlns='http://www.w3.org/2000/svg' fill='none'
                         viewBox='0 0 24 24'>
                        <use href='#lbaic-settings-chatbot-avatar-default'/>
                    </svg>
                );
            }
            break;
        case 'moderator':
            sender.name = __('Moderator', 'limb-chatbot');
            // TODO update the icon
            sender.icon = (
                <svg className='lbaic-settings-chats-avatar-i' xmlns='http://www.w3.org/2000/svg' fill='none'
                     viewBox='0 0 24 24'>
                    <use href='#lbaic-settings-chatbot-avatar-default'/>
                </svg>
            );
            break;
        default:
            break;
    }

    /**
     * User message actions
     */
    const hasUserMessageActions = false;

    /**
     * Assistant message actions
     */
    // Confidence
    const confidenceMeta = message.metas?.find(item => item.meta_key === 'confidence');
    let confidence;
    if (confidenceMeta) {
        confidence = (confidenceMeta?.meta_value || 0) * 100;
    }
    // Sources
    const sourcesMeta = message.metas?.find(item => item.meta_key === 'dataset_entry_sources');
    let sources;
    if (sourcesMeta) {
        sources = sourcesMeta?.meta_value?.length || 0;
    }
    // Show assistant message actions
    const hasAssistantMessageActions = Boolean(confidenceMeta || sourcesMeta);

    // Check for agent status content types
    const hasAgentJoined = message.content?.some(
        item => item.type === AGENT_JOINED_TYPE && item.slack_connection?.value === 'success'
    );
    const hasAgentLeft = message.content?.some(item => item.type === AGENT_LEFT_TYPE);

    // Get agent names for badges
    const joinedAgentName = joinedAgent?.name || __('Agent', 'limb-chatbot');
    const leftAgentName = leftAgent?.name || __('Agent', 'limb-chatbot');

    return (
        <>
            {/*Agent left indicator - shown before disconnect message*/}
            {hasAgentLeft && (
                <div className="lbaic-settings-chats-message-assistant-joined agent-left">
                    <Badge label={sprintf(__('%s left', 'limb-chatbot'), leftAgentName)} custom={true}
                           className="lbaic-settings-badge-red"/>
                </div>
            )}
            <div className={`lbaic-settings-chats-message ${message.role === 'user' ? 'user' : 'ai'}`}>
                {/*Sender name*/}
                {isNewRole && (
                    <div
                        className="lbaic-settings-chats-column lbaic-settings-chats-message-head lbaic-settings-chats-mb-7">
                        <div
                            className="lbaic-settings-chats-column lbaic-settings-chats-column-gap-3.5 lbaic-settings-chats-message-title"
                            onClick={handleUserClick}
                        >
                            <div className='lbaic-settings-chats-avatar'>
                                {sender.iconIsImage ? (
                                    sender.icon
                                ) : (
                                    <div className='lbaic-settings-chats-avatar-in'>{sender.icon}</div>
                                )}
                            </div>
                            <div
                                className="lbaic-settings-chats-column lbaic-settings-chats-column-gap-3.5 lbaic-settings-chats-message-title">
                                <span className="lbaic-settings-chats-desc">{sender.name}</span>
                            </div>
                        </div>
                        <div className="lbaic-settings-chats-message-time">
                            <span
                                className='lbaic-settings-chats-desc'>{getSmartFormatedDate(message.created_at)}</span>
                        </div>
                    </div>
                )}
                {/*Message content*/}
                <div className="lbaic-settings-chats-message-body">
                    <div className="lbaic-settings-chats-message-body-in">
                        {message.content?.length > 0 ? (
                            message.content
                                .filter(content => RENDER_CONTENT_TYPES.includes(content.type))
                                .map((content, index) => {
                                    switch (content.type) {
                                        case 'text':
                                            // Text
                                            return (
                                                <div
                                                    key={content.type + index}
                                                    className='lbaic-settings-chats-message-text'
                                                    dangerouslySetInnerHTML={{__html: prepareChatbotMessage(content.text.value)}}
                                                />
                                            );
                                        case 'attachment':
                                            if (isImage(content.attachment.mime_type)) {
                                                // Image
                                                return (
                                                    <img
                                                        key={content.type + index}
                                                        className='lbaic-settings-chats-message-img'
                                                        src={content.attachment.value}
                                                        alt=''
                                                    />
                                                );
                                            } else {
                                                // File
                                                return (
                                                    <>
                                                        <div
                                                            key={content.type + index + 'info'}
                                                            className='lbaic-settings-chats-message-file-info'
                                                        >
                                                        <span
                                                            className='lbaic-settings-chats-message-file-name'>{`File name ${index}`}</span>
                                                            <span
                                                                className='lbaic-settings-chats-message-file-size'>{getBase64FormatedSize(content.attachment.value)}</span>
                                                        </div>
                                                        <div
                                                            key={content.type + index + 'icon'}
                                                            className='lbaic-settings-chats-message-in lbaic-settings-chats-message-file'
                                                        >
                                                            <div className='lbaic-settings-chats-message-file-in'>
                                                                <svg className='lbaic-settings-chats-message-file-i'
                                                                     xmlns='http://www.w3.org/2000/svg'
                                                                     viewBox='0 0 48 48'>
                                                                    <use href='#lbaic-settings-chats-file'/>
                                                                </svg>
                                                            </div>
                                                        </div>
                                                    </>
                                                );
                                            }
                                        case 'audio':
                                            // Audio
                                            const src = `data:${content.audio.mime_type};base64,${content.audio.value}`;
                                            return (
                                                <audio
                                                    key={content.type + index}
                                                    className='lbaic-settings-chats-message-audio'
                                                    controls
                                                >
                                                    <source src={src} type={content.audio.mime_type}/>
                                                    {__("Your browser does not support the audio element.", 'limb-chatbot')}
                                                </audio>
                                            );
                                        case 'action_submission':
                                            // Action submission
                                            if (!content.action_submission) {
                                                return null;
                                            }
                                            const {message, data_fields, success} = content.action_submission;
                                            const isSuccess = success !== false; // Default to true if not explicitly false
                                            const iconName = isSuccess ? 'success' : 'error';

                                            return (
                                                <div
                                                    key={content.type + index}
                                                    className='lbaic-settings-chats-message-action-submission'
                                                >
                                                    <div className={`lbaic-settings-chats-message-action-submission-status${isSuccess ? ' success' : ' error'}`}>
                                                        <svg className='lbaic-settings-chats-message-action-submission-status-i' xmlns='http://www.w3.org/2000/svg'>
                                                            <use href={`#lbaic-settings-chats-action-submission-${iconName}`}/>
                                                        </svg>
                                                    </div>
                                                    <div className='lbaic-settings-chats-message-action-submission-content'>
                                                        {message && (
                                                            <div className='lbaic-settings-chats-message-info' dangerouslySetInnerHTML={{__html: prepareChatbotMessage(message)}}></div>
                                                        )}
                                                        {data_fields && Object.keys(data_fields).length > 0 && (
                                                            <>
                                                                <div className='lbaic-settings-chats-message-data-divider'></div>
                                                                <div className='lbaic-settings-chats-message-data-fields'>
                                                                    {Object.entries(data_fields).map(([key, value]) => (
                                                                        <div key={key} className='lbaic-settings-chats-message-data-field-row'>
                                                                            <span className='lbaic-settings-chats-message-data-field-label'>{key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())}:</span>
                                                                            <span className='lbaic-settings-chats-message-data-field-value'>{value || 'None'}</span>
                                                                        </div>
                                                                    ))}
                                                                </div>
                                                            </>
                                                        )}
                                                    </div>
                                                </div>
                                            );
                                        default:
                                            return null;
                                    }
                                })
                        ) : (
                            <div className='lbaic-settings-chats-message-text'>{__("No content", "limb-chatbot")}</div>
                        )}
                        {/*Message actions*/}
                        {(hasUserMessageActions || hasAssistantMessageActions) && (
                            <div className="lbaic-settings-chats-message-actions">
                                {hasUserMessageActions && message.role === 'user' && (
                                    <>
                                        {/*Create ticket*/}
                                        {/*<button
                                        type='button'
                                        className="lbaic-settings-chats-column lbaic-settings-chats-column lbaic-settings-chats-column-gap-5.25 lbaic-settings-chats-action lbaic-settings-chats-message-actions-in">
                                        <svg className='lbaic-settings-chats-action-i lbaic-settings-chats-action-i-stroke'
                                             xmlns='http://www.w3.org/2000/svg' fill='none'
                                             viewBox='0 0 24 24'>
                                            <use href='#lbaic-settings-ticket'/>
                                        </svg>
                                        <span className='lbaic-settings-chats-desc'>{__('Create Ticket', 'limb-chatbot')}</span>
                                    </button>*/}
                                        {/*Add knowledge*/}
                                        {/*<button
                                        type='button'
                                        className="lbaic-settings-chats-column lbaic-settings-chats-column lbaic-settings-chats-column-gap-5.25 lbaic-settings-chats-action lbaic-settings-chats-message-actions-in">
                                        <svg className='lbaic-settings-chats-action-i lbaic-settings-chats-action-i-stroke'
                                             xmlns='http://www.w3.org/2000/svg' fill='none'
                                             viewBox='0 0 24 24'>
                                            <use href='#lbaic-settings-book'/>
                                        </svg>
                                        <span className='lbaic-settings-chats-desc'>{__('Add Knowledge', 'limb-chatbot')}</span>
                                    </button>*/}
                                    </>
                                )}
                                {hasAssistantMessageActions && message.role === 'assistant' && (
                                    <>
                                        {/*Confidence*/}
                                        {Boolean(confidenceMeta) && (
                                            <button
                                                type='button'
                                                className="lbaic-settings-chats-column lbaic-settings-chats-column lbaic-settings-chats-column-gap-5.25 lbaic-settings-chats-action lbaic-settings-chats-message-actions-in">
                                                <svg
                                                    className='lbaic-settings-chats-action-i lbaic-settings-chats-action-i-stroke'
                                                    xmlns='http://www.w3.org/2000/svg' fill='none'
                                                    viewBox='0 0 24 24'>
                                                    <use href='#lbaic-settings-circle-nested'/>
                                                </svg>
                                                <span
                                                    className='lbaic-settings-chats-desc'>{sprintf(__('%d%%', 'limb-chatbot'), confidence)}</span>
                                            </button>
                                        )}
                                        {/*Sources*/}
                                        {Boolean(sourcesMeta) && (
                                            <button
                                                type='button'
                                                className="lbaic-settings-chats-column lbaic-settings-chats-column lbaic-settings-chats-column-gap-5.25 lbaic-settings-chats-action lbaic-settings-chats-message-actions-in"
                                                onClick={() => setShowSourcesPopup(true)}
                                            >
                                                <svg
                                                    className='lbaic-settings-chats-action-i lbaic-settings-chats-action-i-fill'
                                                    xmlns='http://www.w3.org/2000/svg' fill='none'
                                                    viewBox='0 0 24 24'>
                                                    <use href='#lbaic-settings-database'/>
                                                </svg>
                                                <span
                                                    className='lbaic-settings-chats-desc'>{sprintf(__('%d sources', 'limb-chatbot'), sources)}</span>
                                            </button>
                                        )}
                                        {/*<button
                                        type='button'
                                        className="lbaic-settings-chats-column lbaic-settings-chats-column lbaic-settings-chats-column-gap-5.25 lbaic-settings-chats-action lbaic-settings-chats-message-actions-in">
                                        <svg className='lbaic-settings-chats-action-i lbaic-settings-chats-action-i-stroke'
                                             xmlns='http://www.w3.org/2000/svg' fill='none'
                                             viewBox='0 0 24 24'>
                                            <use href='#lbaic-settings-letter'/>
                                        </svg>
                                        <span className='lbaic-settings-chats-desc'>8.5</span>
                                    </button>*/}
                                    </>
                                )}
                            </div>
                        )}
                    </div>
                </div>
            </div>
            {/*Agent joined indicator - shown after connection message*/}
            {hasAgentJoined && (
                <div className="lbaic-settings-chats-message-assistant-joined agent-joined">
                    <Badge label={sprintf(__('%s joined', 'limb-chatbot'), joinedAgentName)} custom={true}
                           className="lbaic-settings-badge-green"/>
                </div>
            )}
            {showSourcesPopup && (
                <MessageSourcesPopup
                    datasetEntries={message.dataset_entries}
                    onClose={() => setShowSourcesPopup(false)}
                    notifications={notifications}
                />
            )}
        </>
    )
}