import CategorizedEmojis, { AllEmojis } from '../assets/emojis';
import React, { useState, useEffect, useRef } from 'react';
import { useConvex, useQuery } from 'convex/react';
import { api } from '../../../../convex/_generated/api';

const EmojiItem = ({ emoji, onSelect }) => (
    <div
        onMouseDown={(e) => e.preventDefault()}
        onClick={() => onSelect && onSelect({ type: 'emoji', ...emoji })}
        title={`:${emoji.name}:`}
        style={{ cursor: 'pointer', padding: '4px', borderRadius: '4px' }}
        onMouseEnter={(e) => e.currentTarget.style.backgroundColor = 'var(--background-modifier-hover)'}
        onMouseLeave={(e) => e.currentTarget.style.backgroundColor = 'transparent'}
    >
        <img src={emoji.src} alt={emoji.name} style={{ width: '32px', height: '32px' }} loading="lazy" />
    </div>
);

const emojiGridStyle = { display: 'grid', gridTemplateColumns: 'repeat(8, 1fr)', gap: '4px' };

const GifContent = ({ search, results, categories, onSelect, onCategoryClick }) => {
    if (search || results.length > 0) {
        return (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
                {results.map(gif => (
                    <img
                        key={gif.id}
                        src={gif.media_formats?.tinygif?.url || gif.media_formats?.gif?.url}
                        alt={gif.title}
                        style={{ width: '100%', borderRadius: '4px', cursor: 'pointer' }}
                        onMouseDown={(e) => e.preventDefault()}
                        onClick={() => onSelect(gif.media_formats?.gif?.url || gif.src)}
                    />
                ))}
                {results.length === 0 && <div style={{ color: 'var(--header-secondary)', gridColumn: 'span 2', textAlign: 'center' }}>No GIFs found</div>}
            </div>
        );
    }

    return (
        <div>
            <div style={{
                backgroundImage: 'linear-gradient(to right, #4a90e2, #9013fe)',
                borderRadius: '4px',
                padding: '20px',
                marginBottom: '12px',
                color: '#fff',
                fontWeight: 'bold',
                fontSize: '16px',
                textAlign: 'center',
                cursor: 'pointer'
            }}>
                Favorites
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
                {categories.map(cat => (
                    <div
                        key={cat.name}
                        onClick={() => onCategoryClick(cat.name)}
                        style={{
                            position: 'relative',
                            height: '100px',
                            borderRadius: '4px',
                            overflow: 'hidden',
                            cursor: 'pointer',
                            backgroundColor: 'var(--bg-tertiary)'
                        }}
                    >
                        <video
                            src={cat.src}
                            autoPlay
                            loop
                            muted
                            style={{ width: '100%', height: '100%', objectFit: 'cover', opacity: 0.6 }}
                        />
                        <div style={{
                            position: 'absolute',
                            top: 0, left: 0, right: 0, bottom: 0,
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            backgroundColor: 'rgba(0,0,0,0.3)',
                            color: '#fff',
                            fontWeight: 'bold',
                            textTransform: 'capitalize'
                        }}>
                            {cat.name}
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
};

const EmojiContent = ({ search, onSelect, collapsedCategories, toggleCategory, customEmojis = [] }) => {
    if (search) {
        const q = search.toLowerCase().replace(/:/g, '');
        const customFiltered = customEmojis.filter(e => e.name.toLowerCase().includes(q));
        const builtinFiltered = AllEmojis.filter(e => e.name.toLowerCase().includes(q));
        const filtered = [...customFiltered, ...builtinFiltered].slice(0, 100);
        return (
            <div className="emoji-grid" style={{ height: '100%' }}>
                <div style={emojiGridStyle}>
                    {filtered.map((emoji, idx) => (
                        <EmojiItem key={idx} emoji={emoji} onSelect={onSelect} />
                    ))}
                </div>
            </div>
        );
    }

    const CategoryHeader = ({ name, collapsed }) => (
        <div
            onClick={() => toggleCategory(name)}
            style={{
                display: 'flex',
                alignItems: 'center',
                cursor: 'pointer',
                marginBottom: '8px',
                padding: '4px',
                borderRadius: '4px'
            }}
            onMouseEnter={(e) => e.currentTarget.style.backgroundColor = 'var(--background-modifier-hover)'}
            onMouseLeave={(e) => e.currentTarget.style.backgroundColor = 'transparent'}
        >
            <svg
                xmlns="http://www.w3.org/2000/svg"
                width="12"
                height="12"
                viewBox="0 0 24 24"
                fill="none"
                stroke="var(--header-secondary)"
                strokeWidth="3"
                strokeLinecap="round"
                strokeLinejoin="round"
                style={{
                    marginRight: '8px',
                    transform: collapsed ? 'rotate(-90deg)' : 'rotate(0deg)',
                    transition: 'transform 0.2s'
                }}
            >
                <polyline points="6 9 12 15 18 9"></polyline>
            </svg>
            <h3 style={{
                color: 'var(--header-secondary)',
                fontSize: '12px',
                textTransform: 'uppercase',
                fontWeight: 700,
                margin: 0
            }}>
                {name}
            </h3>
        </div>
    );

    return (
        <div className="emoji-grid" style={{ height: '100%' }}>
            {customEmojis.length > 0 && (
                <div style={{ marginBottom: '8px' }}>
                    <CategoryHeader name="Custom" collapsed={collapsedCategories['Custom']} />
                    {!collapsedCategories['Custom'] && (
                        <div style={emojiGridStyle}>
                            {customEmojis.map((emoji) => (
                                <EmojiItem key={emoji._id || emoji.name} emoji={emoji} onSelect={onSelect} />
                            ))}
                        </div>
                    )}
                </div>
            )}
            {Object.entries(CategorizedEmojis).map(([category, emojis]) => (
                <div key={category} style={{ marginBottom: '8px' }}>
                    <CategoryHeader name={category} collapsed={collapsedCategories[category]} />
                    {!collapsedCategories[category] && (
                        <div style={emojiGridStyle}>
                            {emojis.map((emoji, idx) => (
                                <EmojiItem key={idx} emoji={emoji} onSelect={onSelect} />
                            ))}
                        </div>
                    )}
                </div>
            ))}
        </div>
    );
};

const initialCollapsed = Object.fromEntries(
    Object.keys(CategorizedEmojis).map(cat => [cat, true])
);

const GifPicker = ({ onSelect, onClose, initialTab, currentTab, onTabChange }) => {
    const [search, setSearch] = useState('');
    const [categories, setCategories] = useState([]);
    const [results, setResults] = useState([]);
    const [loading, setLoading] = useState(false);
    const [internalActiveTab, setInternalActiveTab] = useState(initialTab || 'GIFs');
    const [collapsedCategories, setCollapsedCategories] = useState(initialCollapsed);
    const inputRef = useRef(null);

    const convex = useConvex();
    const customEmojis = useQuery(api.customEmojis.list) || [];

    const activeTab = currentTab !== undefined ? currentTab : internalActiveTab;
    const setActiveTab = (tab) => {
        if (onTabChange) onTabChange(tab);
        if (currentTab === undefined) setInternalActiveTab(tab);
    };

    useEffect(() => {
        convex.action(api.gifs.categories, {})
            .then(data => {
                if (data.categories) setCategories(data.categories);
            })
            .catch(err => console.error('Failed to load categories', err));

        if (inputRef.current) inputRef.current.focus();
    }, []);

    useEffect(() => {
        const fetchResults = async () => {
            if (!search || activeTab !== 'GIFs') {
                setResults([]);
                return;
            }
            setLoading(true);
            try {
                const data = await convex.action(api.gifs.search, { q: search });
                setResults(data.results || []);
            } catch (err) {
                console.error(err);
            } finally {
                setLoading(false);
            }
        };

        const timeout = setTimeout(fetchResults, 500);
        return () => clearTimeout(timeout);
    }, [search, activeTab]);

    const toggleCategory = (categoryName) => {
        setCollapsedCategories(prev => ({
            ...prev,
            [categoryName]: !prev[categoryName]
        }));
    };

    return (
        <div
            className="gif-picker"
            style={{
                position: 'absolute',
                bottom: '50px',
                right: '0',
                width: '400px',
                height: '450px',
                backgroundColor: 'var(--embed-background)',
                borderRadius: '8px',
                boxShadow: '0 8px 16px rgba(0,0,0,0.24)',
                display: 'flex',
                flexDirection: 'column',
                overflow: 'hidden',
                zIndex: 1000
            }}
            onClick={(e) => e.stopPropagation()}
        >
            {/* Header / Tabs */}
            <div style={{ padding: '16px 16px 8px 16px', display: 'flex', gap: '16px', borderBottom: '1px solid var(--bg-tertiary)' }}>
                {['GIFs', 'Stickers', 'Emoji'].map(tab => (
                    <button
                        key={tab}
                        onClick={() => setActiveTab(tab)}
                        style={{
                            background: 'none',
                            border: 'none',
                            color: activeTab === tab ? 'var(--header-primary)' : 'var(--header-secondary)',
                            fontWeight: 500,
                            cursor: 'pointer',
                            fontSize: '14px',
                            paddingBottom: '4px',
                            borderBottom: activeTab === tab ? '2px solid var(--brand-experiment)' : '2px solid transparent'
                        }}
                    >
                        {tab}
                    </button>
                ))}
            </div>

            {/* Search Bar */}
            <div style={{ padding: '8px 16px' }}>
                <div style={{
                    backgroundColor: 'var(--bg-tertiary)',
                    borderRadius: '4px',
                    display: 'flex',
                    alignItems: 'center',
                    padding: '0 8px'
                }}>
                    <input
                        ref={inputRef}
                        type="text"
                        placeholder={activeTab === 'Emoji' ? "Find the perfect emoji" : "Search Tenor"}
                        value={search}
                        onChange={(e) => setSearch(e.target.value)}
                        onKeyDown={(e) => {
                            if (e.key === 'Enter') {
                                e.preventDefault();
                                e.stopPropagation();
                            }
                        }}
                        style={{
                            flex: 1,
                            backgroundColor: 'transparent',
                            border: 'none',
                            color: 'var(--text-normal)',
                            padding: '8px',
                            fontSize: '14px',
                            outline: 'none'
                        }}
                    />
                    <div style={{ padding: '4px' }}>
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--header-secondary)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                            <circle cx="11" cy="11" r="8"></circle>
                            <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
                        </svg>
                    </div>
                </div>
            </div>

            {/* Content Area */}
            <div style={{ flex: 1, overflowY: 'auto', padding: '0 16px 16px 16px' }}>
                {loading ? (
                    <div style={{ color: 'var(--header-secondary)', textAlign: 'center', padding: '20px' }}>Loading...</div>
                ) : activeTab === 'GIFs' ? (
                    <GifContent search={search} results={results} categories={categories} onSelect={onSelect} onCategoryClick={setSearch} />
                ) : (
                    <EmojiContent search={search} onSelect={onSelect} collapsedCategories={collapsedCategories} toggleCategory={toggleCategory} customEmojis={customEmojis} />
                )}
            </div>
        </div>
    );
};

export default GifPicker;
