/**
 * Tag Selector Component
 * Chip-based tag selector with server-fetched tags + inline new tag input
 */

import { useState, useEffect, useRef } from 'react';
import { fetchTags, getRecentTags, saveRecentTags } from '../shared/api-client';

interface TagSelectorProps {
    selectedTags: string[];
    onChange: (tags: string[]) => void;
}

export function TagSelector({ selectedTags, onChange }: TagSelectorProps) {
    const [availableTags, setAvailableTags] = useState<string[]>([]);
    const [isAdding, setIsAdding] = useState(false);
    const [newTag, setNewTag] = useState('');
    const [loading, setLoading] = useState(true);
    const inputRef = useRef<HTMLInputElement>(null);

    useEffect(() => {
        loadTags();
    }, []);

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

    const loadTags = async () => {
        setLoading(true);
        try {
            const [serverTags, recentTags] = await Promise.all([
                fetchTags(),
                getRecentTags(),
            ]);
            // Merge: recent first, then server tags
            const merged = [...new Set([...recentTags, ...serverTags])];
            setAvailableTags(merged);
        } catch {
            // Fallback to empty
        }
        setLoading(false);
    };

    const toggleTag = (tag: string) => {
        if (selectedTags.includes(tag)) {
            onChange(selectedTags.filter((t) => t !== tag));
        } else {
            onChange([...selectedTags, tag]);
            // Save to recent
            saveRecentTags([tag, ...selectedTags]);
        }
    };

    const addNewTag = () => {
        const cleaned = newTag.trim().replace(/^#/, '');
        if (cleaned && !selectedTags.includes(cleaned)) {
            onChange([...selectedTags, cleaned]);
            if (!availableTags.includes(cleaned)) {
                setAvailableTags([cleaned, ...availableTags]);
            }
            saveRecentTags([cleaned, ...selectedTags]);
        }
        setNewTag('');
        setIsAdding(false);
    };

    const handleKeyDown = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            addNewTag();
        } else if (e.key === 'Escape') {
            setNewTag('');
            setIsAdding(false);
        }
    };

    // Show max 12 tags to keep UI compact
    const displayTags = availableTags.slice(0, 12);

    return (
        <div className="form-group">
            <label className="label">Tags</label>
            <div className="tag-chips">
                {loading ? (
                    <span style={{ fontSize: '11px', color: 'var(--muted-foreground)' }}>
                        Loading tags...
                    </span>
                ) : (
                    <>
                        {displayTags.map((tag) => (
                            <button
                                key={tag}
                                type="button"
                                className={`tag-chip ${selectedTags.includes(tag) ? 'selected' : ''}`}
                                onClick={() => toggleTag(tag)}
                            >
                                <span className="tag-chip-icon">#</span>
                                {tag}
                            </button>
                        ))}

                        {isAdding ? (
                            <div className="tag-input-inline">
                                <span className="tag-chip-icon">#</span>
                                <input
                                    ref={inputRef}
                                    type="text"
                                    className="tag-input-field"
                                    value={newTag}
                                    onChange={(e) => setNewTag(e.target.value)}
                                    onKeyDown={handleKeyDown}
                                    onBlur={addNewTag}
                                    placeholder="new tag"
                                />
                            </div>
                        ) : (
                            <button
                                type="button"
                                className="tag-input-inline"
                                onClick={() => setIsAdding(true)}
                            >
                                + Add
                            </button>
                        )}
                    </>
                )}
            </div>
            {selectedTags.length > 0 && (
                <div className="label-hint">
                    {selectedTags.length} tag{selectedTags.length > 1 ? 's' : ''} selected
                </div>
            )}
        </div>
    );
}
