import React, { useState, useRef, useCallback } from 'react';
import ReactDOM from 'react-dom';
import ColoredIcon from './ColoredIcon';
import settingsIcon from '../assets/icons/settings.svg';

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

const MobileChannelDrawer = ({ channel, isUnread, onMarkAsRead, onEditChannel, onClose }) => {
    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((cb) => {
        dismiss();
        setTimeout(cb, 220);
    }, [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 isVoice = channel?.type === 'voice';

    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>

                {/* Channel header */}
                <div style={{
                    padding: '4px 16px 12px',
                    display: 'flex',
                    alignItems: 'center',
                    gap: 8,
                }}>
                    {isVoice ? (
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="var(--interactive-normal)">
                            <path d="M11.383 3.07904C11.009 2.92504 10.579 3.01004 10.293 3.29604L6.586 7.00304H3C2.45 7.00304 2 7.45304 2 8.00304V16.003C2 16.553 2.45 17.003 3 17.003H6.586L10.293 20.71C10.579 20.996 11.009 21.082 11.383 20.927C11.757 20.772 12 20.407 12 20.003V4.00304C12 3.59904 11.757 3.23404 11.383 3.07904ZM14 5.00304V7.00304C16.757 7.00304 19 9.24604 19 12.003C19 14.76 16.757 17.003 14 17.003V19.003C17.86 19.003 21 15.863 21 12.003C21 8.14304 17.86 5.00304 14 5.00304ZM14 9.00304V15.003C15.654 15.003 17 13.657 17 12.003C17 10.349 15.654 9.00304 14 9.00304Z" />
                        </svg>
                    ) : (
                        <span style={{ color: 'var(--interactive-normal)', fontSize: 20, fontWeight: 500 }}>#</span>
                    )}
                    <span style={{
                        color: 'var(--text-normal)',
                        fontSize: 16,
                        fontWeight: 600,
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                    }}>
                        {channel?.name}
                    </span>
                </div>

                {/* Actions */}
                <div className="mobile-drawer-card">
                    <button
                        className={`mobile-drawer-action${!isUnread ? ' mobile-drawer-action-disabled' : ''}`}
                        onClick={isUnread ? () => handleAction(onMarkAsRead) : undefined}
                        disabled={!isUnread}
                    >
                        <svg width="20" height="20" viewBox="0 0 24 24" fill={isUnread ? ICON_COLOR_DEFAULT : 'var(--text-muted)'}>
                            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" />
                        </svg>
                        <span>Mark As Read</span>
                    </button>
                    <button className="mobile-drawer-action" onClick={() => handleAction(onEditChannel)}>
                        <ColoredIcon src={settingsIcon} color={ICON_COLOR_DEFAULT} size="20px" />
                        <span>Edit Channel</span>
                    </button>
                </div>
            </div>
        </>,
        document.body
    );
};

export default MobileChannelDrawer;
