import React, { useState, useRef, useCallback } from 'react';
import ReactDOM from 'react-dom';
import { EmojieIcon, EditIcon, ReplyIcon, DeleteIcon, PinIcon } from '../assets/icons';
import { getEmojiUrl } from '../assets/emojis';
import ColoredIcon from './ColoredIcon';

const ICON_COLOR_DEFAULT = 'hsl(240, 4.294%, 68.039%)';

const QUICK_REACTIONS = [
    { name: 'thumbsup', category: 'people' },
    { name: 'fire', category: 'nature' },
    { name: 'heart', category: 'symbols' },
    { name: 'joy', category: 'people' },
    { name: 'sob', category: 'people' },
    { name: 'eyes', category: 'people' },
];

const CopyIcon = () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
        <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/>
    </svg>
);

const MobileMessageDrawer = ({ message, isOwner, isAttachment, canDelete, onClose, onAction, onQuickReaction }) => {
    const [closing, setClosing] = useState(false);
    const drawerRef = useRef(null);
    const dragStartY = useRef(null);
    const dragCurrentY = useRef(null);
    const dragStartTime = useRef(null);

    const dismiss = useCallback(() => {
        setClosing(true);
        setTimeout(onClose, 200);
    }, [onClose]);

    const handleAction = useCallback((action) => {
        onAction(action);
        dismiss();
    }, [onAction, dismiss]);

    const handleQuickReaction = useCallback((name) => {
        onQuickReaction(name);
        dismiss();
    }, [onQuickReaction, dismiss]);

    // Swipe-to-dismiss
    const handleTouchStart = useCallback((e) => {
        dragStartY.current = e.touches[0].clientY;
        dragCurrentY.current = e.touches[0].clientY;
        dragStartTime.current = Date.now();
        if (drawerRef.current) {
            drawerRef.current.style.transition = 'none';
        }
    }, []);

    const handleTouchMove = useCallback((e) => {
        if (dragStartY.current === null) return;
        dragCurrentY.current = e.touches[0].clientY;
        const dy = dragCurrentY.current - dragStartY.current;
        if (dy > 0 && drawerRef.current) {
            drawerRef.current.style.transform = `translateY(${dy}px)`;
        }
    }, []);

    const handleTouchEnd = useCallback(() => {
        if (dragStartY.current === null || !drawerRef.current) return;
        const dy = dragCurrentY.current - dragStartY.current;
        const dt = (Date.now() - dragStartTime.current) / 1000;
        const velocity = dt > 0 ? dy / dt : 0;
        const drawerHeight = drawerRef.current.offsetHeight;
        const threshold = drawerHeight * 0.3;

        if (dy > threshold || velocity > 500) {
            dismiss();
        } else {
            drawerRef.current.style.transition = 'transform 0.2s ease-out';
            drawerRef.current.style.transform = 'translateY(0)';
        }
        dragStartY.current = null;
    }, [dismiss]);

    const isPinned = message?.pinned;

    return ReactDOM.createPortal(
        <>
            <div className="mobile-drawer-overlay" onClick={dismiss} />
            <div
                ref={drawerRef}
                className={`mobile-drawer${closing ? ' mobile-drawer-closing' : ''}`}
                onTouchStart={handleTouchStart}
                onTouchMove={handleTouchMove}
                onTouchEnd={handleTouchEnd}
            >
                <div className="mobile-drawer-handle">
                    <div className="mobile-drawer-handle-bar" />
                </div>

                {/* Quick reactions */}
                <div className="mobile-drawer-reactions">
                    {QUICK_REACTIONS.map(({ name, category }) => (
                        <button
                            key={name}
                            className="mobile-drawer-reaction-btn"
                            onClick={() => handleQuickReaction(name)}
                        >
                            <ColoredIcon src={getEmojiUrl(category, name)} size="24px" color={null} />
                        </button>
                    ))}
                    <button
                        className="mobile-drawer-reaction-btn"
                        onClick={() => handleAction('reaction')}
                    >
                        <ColoredIcon src={EmojieIcon} color={ICON_COLOR_DEFAULT} size="22px" />
                    </button>
                </div>

                <div className="mobile-drawer-separator" />

                {/* Primary actions */}
                <div className="mobile-drawer-card">
                    {isOwner && !isAttachment && (
                        <button className="mobile-drawer-action" onClick={() => handleAction('edit')}>
                            <ColoredIcon src={EditIcon} color={ICON_COLOR_DEFAULT} size="20px" />
                            <span>Edit Message</span>
                        </button>
                    )}
                    <button className="mobile-drawer-action" onClick={() => handleAction('reply')}>
                        <ColoredIcon src={ReplyIcon} color={ICON_COLOR_DEFAULT} size="20px" />
                        <span>Reply</span>
                    </button>
                    {!isAttachment && (
                        <button className="mobile-drawer-action" onClick={() => handleAction('copy')}>
                            <CopyIcon />
                            <span>Copy Text</span>
                        </button>
                    )}
                    <button className="mobile-drawer-action" onClick={() => handleAction('pin')}>
                        <ColoredIcon src={PinIcon} color={ICON_COLOR_DEFAULT} size="20px" />
                        <span>{isPinned ? 'Unpin Message' : 'Pin Message'}</span>
                    </button>
                </div>

                {/* Danger actions */}
                {canDelete && (
                    <div className="mobile-drawer-card">
                        <button className="mobile-drawer-action mobile-drawer-action-danger" onClick={() => handleAction('delete')}>
                            <ColoredIcon src={DeleteIcon} color="#ed4245" size="20px" />
                            <span>Delete Message</span>
                        </button>
                    </div>
                )}
            </div>
        </>,
        document.body
    );
};

export default MobileMessageDrawer;
