/**
 * Tag Selector — shadcn/ui badge chips
 */

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(),
            ]);
            const merged = [...new Set([...recentTags, ...serverTags])];
            setAvailableTags(merged);
        } catch {
            // Fallback
        }
        setLoading(false);
    };

    const toggleTag = (tag: string) => {
        if (selectedTags.includes(tag)) {
            onChange(selectedTags.filter((t) => t !== tag));
        } else {
            onChange([...selectedTags, tag]);
            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);
        }
    };

    const displayTags = availableTags.slice(0, 10);

    return (
        <div className="form-group">
            <label className="label">Tags</label>
            <div className="tag-chips">
                {loading ? (
                    <span style={{ fontSize: '11px', color: 'var(--muted-foreground)' }}>
                        Loading...
                    </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="tag"
                                />
                            </div>
                        ) : (
                            <button
                                type="button"
                                className="tag-input-inline"
                                onClick={() => setIsAdding(true)}
                            >
                                + Add
                            </button>
                        )}
                    </>
                )}
            </div>
        </div>
    );
}
