import React, { useState, useEffect, useRef } from 'react';
import { useConvex } from 'convex/react';
import { api } from '../../../../convex/_generated/api';
import Tooltip from './Tooltip';
import Avatar from './Avatar';
import ColoredIcon from './ColoredIcon';
import { useOnlineUsers } from '../contexts/PresenceContext';
import friendsIcon from '../assets/icons/friends.svg';

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

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

const getUserColor = (username) => {
    if (!username) return '#5865F2';
    const colors = ['#5865F2', '#EBA7CD', '#57F287', '#FEE75C', '#EB459E', '#ED4245'];
    let hash = 0;
    for (let i = 0; i < username.length; i++) {
        hash = username.charCodeAt(i) + ((hash << 5) - hash);
    }
    return colors[Math.abs(hash) % colors.length];
};

const DMList = ({ dmChannels, activeDMChannel, onSelectDM, onOpenDM, voiceStates }) => {
    const [showUserPicker, setShowUserPicker] = useState(false);
    const [allUsers, setAllUsers] = useState([]);
    const [searchQuery, setSearchQuery] = useState('');
    const [searchFocused, setSearchFocused] = useState(false);
    const searchRef = useRef(null);
    const searchInputRef = useRef(null);
    const { resolveStatus } = useOnlineUsers();

    const convex = useConvex();

    const handleOpenUserPicker = async () => {
        setShowUserPicker(true);
        setSearchQuery('');
        try {
            const data = await convex.query(api.auth.getPublicKeys, {});
            const myId = localStorage.getItem('userId');
            setAllUsers(data.filter(u => u.id !== myId));
        } catch (err) {
            console.error(err);
        }
    };

    const handleSearchFocus = async () => {
        setSearchFocused(true);
        if (allUsers.length === 0) {
            try {
                const data = await convex.query(api.auth.getPublicKeys, {});
                const myId = localStorage.getItem('userId');
                setAllUsers(data.filter(u => u.id !== myId));
            } catch (err) {
                console.error(err);
            }
        }
    };

    useEffect(() => {
        if (showUserPicker && searchRef.current) {
            searchRef.current.focus();
        }
    }, [showUserPicker]);

    const filteredUsers = allUsers.filter(u =>
        u.username?.toLowerCase().includes(searchQuery.toLowerCase())
    );

    const handleCloseDM = (e, dm) => {
        e.stopPropagation();
        // If closing the active DM, switch back to friends
        if (activeDMChannel?.channel_id === dm.channel_id) {
            onSelectDM('friends');
        }
    };

    return (
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
            
            {/* Search Input */}
            <div className="dm-search-wrapper">
                <input
                    ref={searchInputRef}
                    type="text"
                    className="dm-search-input"
                    placeholder="Find or start a conversation"
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    onFocus={handleSearchFocus}
                    onBlur={() => {
                        setTimeout(() => setSearchFocused(false), 200);
                    }}
                />
                {searchFocused && searchQuery && filteredUsers.length > 0 && (
                    <div className="dm-search-dropdown">
                        {filteredUsers.slice(0, 8).map(user => (
                            <div
                                key={user.id}
                                className="dm-search-result"
                                onMouseDown={(e) => {
                                    e.preventDefault();
                                    setSearchQuery('');
                                    setSearchFocused(false);
                                    onOpenDM(user.id, user.username);
                                }}
                            >
                                <Avatar username={user.username} size={24} style={{ marginRight: '8px' }} />
                                <span>{user.username}</span>
                            </div>
                        ))}
                    </div>
                )}
            </div>

            {/* User Picker Modal */}
            {showUserPicker && (
                <div style={{
                    position: 'absolute', top: 0, left: 0, right: 0, bottom: 0,
                    backgroundColor: 'rgba(0,0,0,0.7)', zIndex: 100,
                    display: 'flex', alignItems: 'center', justifyContent: 'center'
                }}
                onClick={() => setShowUserPicker(false)}
                >
                    <div
                        style={{
                            backgroundColor: 'var(--bg-primary)', borderRadius: '8px', padding: '16px',
                            width: '400px', maxHeight: '500px', display: 'flex', flexDirection: 'column'
                        }}
                        onClick={e => e.stopPropagation()}
                    >
                        <h3 style={{ color: 'var(--header-primary)', margin: '0 0 4px 0', fontSize: '16px' }}>Select a User</h3>
                        <p style={{ color: 'var(--header-secondary)', fontSize: '12px', margin: '0 0 12px 0' }}>Start a new direct message conversation.</p>
                        <input
                            ref={searchRef}
                            type="text"
                            placeholder="Type a username..."
                            value={searchQuery}
                            onChange={e => setSearchQuery(e.target.value)}
                            style={{
                                width: '100%', backgroundColor: 'var(--bg-tertiary)', border: '1px solid var(--border-subtle)',
                                borderRadius: '4px', color: 'var(--text-normal)', padding: '8px 12px', fontSize: '14px',
                                outline: 'none', marginBottom: '8px', boxSizing: 'border-box'
                            }}
                        />
                        <div style={{ flex: 1, overflowY: 'auto', maxHeight: '300px' }}>
                            {filteredUsers.map(user => (
                                <div
                                    key={user.id}
                                    className="dm-picker-user"
                                    onClick={() => { setShowUserPicker(false); onOpenDM(user.id, user.username); }}
                                >
                                    <Avatar username={user.username} size={32} style={{ marginRight: '12px' }} />
                                    <span style={{ fontWeight: '500' }}>{user.username}</span>
                                </div>
                            ))}
                            {filteredUsers.length === 0 && (
                                <div style={{ color: 'var(--text-muted)', textAlign: 'center', padding: '16px', fontSize: '13px' }}>
                                    No users found.
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            )}

            {/* Friends Button */}
            <div
                className={`dm-friends-btn ${!activeDMChannel ? 'active' : ''}`}
                onClick={() => onSelectDM('friends')}
            >
                <div style={{ marginRight: '12px' }}>
                    <ColoredIcon src={friendsIcon} color="var(--interactive-normal)" size="24px" />
                </div>
                <span style={{ fontWeight: 500 }}>Friends</span>
            </div>

            {/* DM List Header */}
            <div style={{ fontFamily: 'gg sans', display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 16px 8px', color: '#96989d', fontSize: '11px', fontWeight: 'bold', borderTop: 'solid 1px var(--app-frame-border)'}}>
                <span>Direct Messages</span>
            </div>

            {/* DM Channel List */}
            <div style={{ flex: 1, overflowY: 'auto', padding: '0 8px 8px' }}>
                {(dmChannels || []).map(dm => {
                    const isActive = activeDMChannel?.channel_id === dm.channel_id;
                    const effectiveStatus = resolveStatus(dm.other_user_status, dm.other_user_id);
                    return (
                        <div
                            key={dm.channel_id}
                            className={`dm-item ${isActive ? 'dm-item-active' : ''}`}
                            onClick={() => onSelectDM({ channel_id: dm.channel_id, other_username: dm.other_username })}
                        >
                            <div style={{ display: 'flex', alignItems: 'center', flex: 1, minWidth: 0 }}>
                                <div style={{ position: 'relative', marginRight: '12px', flexShrink: 0 }}>
                                    <Avatar username={dm.other_username} avatarUrl={dm.other_user_avatar_url} size={32} />
                                    <div style={{
                                        position: 'absolute', bottom: -2, right: -2,
                                        width: 10, height: 10, borderRadius: '50%',
                                        backgroundColor: STATUS_COLORS[effectiveStatus] || STATUS_COLORS.offline,
                                        border: '2px solid var(--bg-secondary)'
                                    }} />
                                </div>
                                <div style={{ overflow: 'hidden', flex: 1 }}>
                                    <div style={{ color: isActive ? 'var(--header-primary)' : 'var(--text-normal)', whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden', fontWeight: '500' }}>
                                        {dm.other_username}
                                    </div>
                                    {voiceStates && voiceStates[dm.channel_id]?.length > 0 && (
                                        <div style={{ color: '#3ba55c', fontSize: '11px', fontWeight: '500' }}>
                                            In Call
                                        </div>
                                    )}
                                </div>
                            </div>
                            <div className="dm-close-btn" onClick={(e) => handleCloseDM(e, dm)}>
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                                    <path d="M18.4 4L12 10.4L5.6 4L4 5.6L10.4 12L4 18.4L5.6 20L12 13.6L18.4 20L20 18.4L13.6 12L20 5.6L18.4 4Z"/>
                                </svg>
                            </div>
                        </div>
                    );
                })}
                {(!dmChannels || dmChannels.length === 0) && (
                    <div style={{ color: 'var(--text-muted)', fontSize: '13px', textAlign: 'center', padding: '16px 8px' }}>
                        No DMs yet. Click + to start a conversation.
                    </div>
                )}
            </div>
        </div>
    );
};

export default DMList;
