'use client';

import { useState, useEffect } from 'react';
import { EventTag, PREDEFINED_COLORS } from '@/types/tags';
import { ColorPicker } from './ColorPicker';

interface TagManagerProps {
    selectedTags: EventTag[];
    onTagsChange: (tags: EventTag[]) => void;
    className?: string;
}

export function TagManager({ selectedTags, onTagsChange, className = '' }: TagManagerProps) {
    const [availableTags, setAvailableTags] = useState<EventTag[]>([]);
    const [isCreating, setIsCreating] = useState(false);
    const [newTagName, setNewTagName] = useState('');
    const [newTagColor, setNewTagColor] = useState('#3B82F6');
    const [newTagDescription, setNewTagDescription] = useState('');

    console.log('🏷️ TagManager rendered, selectedTags:', selectedTags);
    console.log('🏷️ Available tags:', availableTags);

    useEffect(() => {
        console.log('🏷️ TagManager mounted, fetching tags...');
        fetchAvailableTags();
    }, []);

    const fetchAvailableTags = async () => {
        try {
            console.log('🔄 Fetching tags from /api/event-tags...');
            const response = await fetch('/api/event-tags');
            console.log('📡 Tags response status:', response.status);

            if (response.ok) {
                const tags = await response.json();
                console.log('✅ Tags loaded:', tags);
                setAvailableTags(tags);
            } else {
                console.error('❌ Failed to fetch tags, status:', response.status);
            }
        } catch (error) {
            console.error('❌ Error fetching tags:', error);
        }
    };

    const createNewTag = async () => {
        if (!newTagName.trim()) return;

        try {
            const response = await fetch('/api/event-tags', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    name: newTagName.trim(),
                    color: newTagColor,
                    description: newTagDescription.trim() || undefined
                })
            });

            if (response.ok) {
                const newTag = await response.json();
                setAvailableTags(prev => [...prev, newTag]);
                setNewTagName('');
                setNewTagDescription('');
                setIsCreating(false);
            }
        } catch (error) {
            console.error('Error creating tag:', error);
        }
    };

    const toggleTag = (tag: EventTag) => {
        const isSelected = selectedTags.some(t => t.id === tag.id);
        if (isSelected) {
            onTagsChange(selectedTags.filter(t => t.id !== tag.id));
        } else {
            onTagsChange([...selectedTags, tag]);
        }
    };

    console.log('🏷️ TagManager render - availableTags:', availableTags.length, 'selectedTags:', selectedTags.length);

    return (
        <div className={`space-y-4 ${className}`}>
            <p className="text-xs text-gray-500">Debug: {availableTags.length} available tags, {selectedTags.length} selected</p>

            {/* תגיות נבחרות */}
            {selectedTags.length > 0 && (
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                        תגיות נבחרות:
                    </label>
                    <div className="flex flex-wrap gap-2">
                        {selectedTags.map(tag => (
                            <span
                                key={tag.id}
                                className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium text-white"
                                style={{ backgroundColor: tag.color }}
                            >
                                {tag.name}
                                <button
                                    type="button"
                                    onClick={() => toggleTag(tag)}
                                    className="ml-2 text-white hover:text-gray-200"
                                    aria-label={`הסר תגית ${tag.name}`}
                                >
                                    ×
                                </button>
                            </span>
                        ))}
                    </div>
                </div>
            )}

            {/* תגיות זמינות */}
            <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                    תגיות זמינות:
                </label>
                <div className="flex flex-wrap gap-2">
                    {availableTags.map(tag => {
                        const isSelected = selectedTags.some(t => t.id === tag.id);
                        return (
                            <button
                                key={tag.id}
                                type="button"
                                onClick={() => toggleTag(tag)}
                                className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-medium transition-colors ${isSelected
                                    ? 'text-white'
                                    : 'text-gray-700 bg-gray-100 hover:bg-gray-200'
                                    }`}
                                style={isSelected ? { backgroundColor: tag.color } : {}}
                            >
                                {tag.name}
                            </button>
                        );
                    })}
                </div>
            </div>

            {/* יצירת תגית חדשה */}
            {!isCreating ? (
                <button
                    type="button"
                    onClick={() => setIsCreating(true)}
                    className="text-blue-600 hover:text-blue-800 text-sm font-medium"
                >
                    + צור תגית חדשה
                </button>
            ) : (
                <div className="border rounded-lg p-4 bg-gray-50">
                    <h4 className="text-sm font-medium text-gray-700 mb-3">צור תגית חדשה</h4>
                    <div className="space-y-3">
                        <div>
                            <label className="block text-xs font-medium text-gray-600 mb-1">
                                שם התגית:
                            </label>
                            <input
                                type="text"
                                value={newTagName}
                                onChange={(e) => setNewTagName(e.target.value)}
                                className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm"
                                placeholder="הזן שם תגית"
                                aria-label="שם התגית"
                            />
                        </div>
                        <div>
                            <label className="block text-xs font-medium text-gray-600 mb-1">
                                צבע:
                            </label>
                            <ColorPicker
                                selectedColor={newTagColor}
                                onColorChange={setNewTagColor}
                            />
                        </div>
                        <div>
                            <label className="block text-xs font-medium text-gray-600 mb-1">
                                תיאור (אופציונלי):
                            </label>
                            <input
                                type="text"
                                value={newTagDescription}
                                onChange={(e) => setNewTagDescription(e.target.value)}
                                className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm"
                                placeholder="הזן תיאור"
                                aria-label="תיאור התגית"
                            />
                        </div>
                        <div className="flex gap-2">
                            <button
                                type="button"
                                onClick={createNewTag}
                                disabled={!newTagName.trim()}
                                className="px-3 py-1 bg-blue-600 text-white text-sm rounded-md hover:bg-blue-700 disabled:opacity-50"
                            >
                                צור
                            </button>
                            <button
                                type="button"
                                onClick={() => {
                                    setIsCreating(false);
                                    setNewTagName('');
                                    setNewTagDescription('');
                                }}
                                className="px-3 py-1 bg-gray-300 text-gray-700 text-sm rounded-md hover:bg-gray-400"
                            >
                                ביטול
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
