import { KeyboardEvent, useEffect, useRef, useState } from 'react';
import classNames from 'classnames';
import { Button, Menu } from '@servicetitan/anvil2';
import IconPlus from '@servicetitan/anvil2/assets/icons/material/round/add.svg';
import IconMic from '@servicetitan/anvil2/assets/icons/material/round/mic.svg';
import IconSend from '@servicetitan/anvil2/assets/icons/material/round/send.svg';
import IconAttachFile from '@servicetitan/anvil2/assets/icons/st/attach_file.svg';

import * as styles from './chat-composer-rich.module.less';

export interface ChatComposerRichProps {
    message?: string;
    /** Callback when user submits a message */
    onSend?: (text: string) => void;
    /** Placeholder text for the input */
    placeholder?: string;
    /** Whether the composer is disabled */
    disabled?: boolean;
    /** Additional CSS class name */
    className?: string;
    onChange: (text: string) => void;
    /** Callback when upload file is selected from menu */
    onUploadFile?: () => void;
    /** Callback when dictate message is selected from menu */
    onDictateMessage?: () => void;
    /** ID for the menu button */
    menuButtonId?: string;
    /** ID for the send icon button */
    sendIconId?: string;
    /** ID for the message input area */
    messageInputId?: string;
}

export const ChatComposerRich = ({
    message,
    onSend,
    onChange,
    placeholder = 'Ask anything...',
    disabled = false,
    className,
    onUploadFile,
    onDictateMessage,
    messageInputId,
    sendIconId,
}: ChatComposerRichProps) => {
    const [isEmpty, setIsEmpty] = useState(true);
    const editorRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (editorRef.current && message) {
            editorRef.current.innerText = message;
        }
    }, [message]);

    const handleInput = () => {
        const text = editorRef.current?.innerText.trim() ?? '';
        setIsEmpty(text.length === 0);
    };

    const handleKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            handleSubmit();
        }
    };

    const handleSubmit = () => {
        if (disabled) {
            return;
        }

        const text = editorRef.current?.innerText.trim() ?? '';
        onChange(text);
        if (!text) {
            return;
        }

        onSend?.(text);

        if (editorRef.current) {
            // Clear content while preserving the element structure
            editorRef.current.innerText = '';
            // Force a reflow to ensure styles are reapplied
        }
        setIsEmpty(true);
    };

    useEffect(() => {
        // Ensure empty placeholder is visible on mount
        setIsEmpty(!editorRef.current?.innerText.trim());
    }, []);

    return (
        <div className={classNames(styles.composerWrapper, className)}>
            <form
                onSubmit={e => e.preventDefault()}
                className={classNames(styles.composerForm, {
                    [styles.disabled]: disabled,
                })}
            >
                {onDictateMessage || onUploadFile ? (
                    <Menu
                        id=""
                        trigger={props => (
                            <Button
                                {...props}
                                type="button"
                                aria-label="Open menu"
                                disabled={disabled}
                                className={styles.iconButton}
                                icon={IconPlus}
                                size="small"
                            />
                        )}
                        disabled={disabled}
                    >
                        <Menu.Item
                            label="Upload file"
                            icon={IconAttachFile}
                            onClick={onUploadFile}
                        />
                        <Menu.Item
                            label="Dictate message"
                            icon={IconMic}
                            onClick={onDictateMessage}
                        />
                    </Menu>
                ) : (
                    <div />
                )}

                <div className={styles.inputWrapper}>
                    <div
                        id={messageInputId}
                        ref={editorRef}
                        contentEditable={!disabled ? 'plaintext-only' : false}
                        role="textbox"
                        aria-multiline="true"
                        aria-label={placeholder}
                        data-placeholder={placeholder}
                        onInput={handleInput}
                        onKeyDown={handleKeyDown}
                        className={styles.input}
                    />
                    {isEmpty && <span className={styles.placeholder}>{placeholder}</span>}
                </div>

                <Button
                    id={sendIconId}
                    size="small"
                    type="button"
                    onClick={handleSubmit}
                    disabled={disabled || isEmpty}
                    className={styles.sendButton}
                    aria-label="Send message"
                    appearance="ghost"
                    icon={IconSend}
                />
            </form>
        </div>
    );
};
