import React, { useState, useRef, useCallback } from 'react';
import ReactDOM from 'react-dom';
import ColoredIcon from './ColoredIcon';
import inviteUserIcon from '../assets/icons/invite_user.svg';
import settingsIcon from '../assets/icons/settings.svg';
import createIcon from '../assets/icons/create.svg';
import createCategoryIcon from '../assets/icons/create_category.svg';

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

const MobileServerDrawer = ({ serverName, serverIconUrl, memberCount, onInvite, onSettings, onCreateChannel, onCreateCategory, 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 initials = serverName ? serverName.split(/\s+/).map(w => w[0]).join('').slice(0, 2).toUpperCase() : '?';

    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>

                {/* Server header */}
                <div className="mobile-server-drawer-header">
                    <div className="mobile-server-drawer-icon">
                        {serverIconUrl ? (
                            <img src={serverIconUrl} alt={serverName} />
                        ) : (
                            <span>{initials}</span>
                        )}
                    </div>
                    <div>
                        <div className="mobile-server-drawer-name">{serverName}</div>
                        <div className="mobile-server-drawer-members">{memberCount} {memberCount === 1 ? 'member' : 'members'}</div>
                    </div>
                </div>

                {/* Actions card 1 */}
                <div className="mobile-drawer-card">
                    <button className="mobile-drawer-action" onClick={() => handleAction(onInvite)}>
                        <ColoredIcon src={inviteUserIcon} color={ICON_COLOR_DEFAULT} size="20px" />
                        <span>Invite People</span>
                    </button>
                    <button className="mobile-drawer-action" onClick={() => handleAction(onSettings)}>
                        <ColoredIcon src={settingsIcon} color={ICON_COLOR_DEFAULT} size="20px" />
                        <span>Server Settings</span>
                    </button>
                </div>

                {/* Actions card 2 */}
                <div className="mobile-drawer-card">
                    <button className="mobile-drawer-action" onClick={() => handleAction(onCreateChannel)}>
                        <ColoredIcon src={createIcon} color={ICON_COLOR_DEFAULT} size="20px" />
                        <span>Create Channel</span>
                    </button>
                    <button className="mobile-drawer-action" onClick={() => handleAction(onCreateCategory)}>
                        <ColoredIcon src={createCategoryIcon} color={ICON_COLOR_DEFAULT} size="20px" />
                        <span>Create Category</span>
                    </button>
                </div>
            </div>
        </>,
        document.body
    );
};

export default MobileServerDrawer;
