import React, { useRef, useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
import { useQuery } from 'convex/react';
import { api } from '../../../../convex/_generated/api';
import Avatar from './Avatar';

const STATUS_LABELS = {
    online: 'Online',
    idle: 'Idle',
    dnd: 'Do Not Disturb',
    invisible: 'Invisible',
    offline: 'Offline',
};

const STATUS_COLORS = {
    online: '#3ba55c',
    idle: '#faa61a',
    dnd: '#ed4245',
    invisible: '#747f8d',
    offline: '#747f8d',
};

const USER_COLORS = ['#5865F2', '#EBA7CD', '#57F287', '#FEE75C', '#EB459E', '#ED4245'];

function getUserColor(name) {
    let hash = 0;
    for (let i = 0; i < name.length; i++) {
        hash = name.charCodeAt(i) + ((hash << 5) - hash);
    }
    return USER_COLORS[Math.abs(hash) % USER_COLORS.length];
}

const UserProfilePopup = ({ userId, username, avatarUrl, status, position, onClose, onSendMessage }) => {
    const popupRef = useRef(null);
    const [note, setNote] = useState('');

    // Fetch member data (roles, aboutMe) for this user
    const allUsers = useQuery(api.auth.getPublicKeys) || [];
    const userData = allUsers.find(u => u.id === userId);

    useEffect(() => {
        const handleClick = (e) => {
            if (popupRef.current && !popupRef.current.contains(e.target)) {
                onClose();
            }
        };
        document.addEventListener('mousedown', handleClick);
        return () => document.removeEventListener('mousedown', handleClick);
    }, [onClose]);

    // Load note from localStorage
    useEffect(() => {
        if (userId) {
            const saved = localStorage.getItem(`note_${userId}`);
            if (saved) setNote(saved);
        }
    }, [userId]);

    const handleNoteChange = (e) => {
        const val = e.target.value;
        setNote(val);
        if (userId) {
            localStorage.setItem(`note_${userId}`, val);
        }
    };

    const userColor = getUserColor(username || 'Unknown');
    const userStatus = status || 'online';
    const resolvedAvatarUrl = avatarUrl || userData?.avatarUrl;
    const aboutMe = userData?.aboutMe;

    const style = {
        position: 'fixed',
        top: Math.min(position.y, window.innerHeight - 420),
        left: Math.min(position.x, window.innerWidth - 320),
        zIndex: 10000,
    };

    return ReactDOM.createPortal(
        <div ref={popupRef} className="user-profile-popup" style={style}>
            <div className="user-profile-banner" style={{ backgroundColor: userColor }} />
            <div className="user-profile-body">
                <div className="user-profile-avatar-wrapper">
                    <Avatar
                        username={username}
                        avatarUrl={resolvedAvatarUrl}
                        size={64}
                        className="user-profile-avatar"
                        style={{ border: '4px solid var(--background-base-lowest)' }}
                    />
                    <div
                        className="user-profile-status-dot"
                        style={{ backgroundColor: STATUS_COLORS[userStatus] }}
                    />
                </div>
                <div className="user-profile-name">{username}</div>
                <div className="user-profile-status-text">
                    {userData?.customStatus || STATUS_LABELS[userStatus] || 'Online'}
                </div>
                <div className="user-profile-divider" />

                <div className="user-profile-section-header">ABOUT ME</div>
                <div className="user-profile-about">
                    {aboutMe || 'No information set.'}
                </div>

                <div className="user-profile-divider" />

                <div className="user-profile-section-header">NOTE</div>
                <textarea
                    className="user-profile-note-input"
                    placeholder="Click to add a note"
                    value={note}
                    onChange={handleNoteChange}
                    rows={2}
                />

                {onSendMessage && (
                    <button
                        className="user-profile-message-btn"
                        onClick={() => { onSendMessage(userId, username); onClose(); }}
                        style={{ marginTop: '8px' }}
                    >
                        Send Message
                    </button>
                )}
            </div>
        </div>,
        document.body
    );
};

export default UserProfilePopup;
