'use client';

import React, { useState, useMemo } from 'react';
import { TagCategory, createCustomTag } from '@/services/tags';
import { X, Plus, Search, Check, Loader2, Sparkles } from 'lucide-react';
import { useI18n } from '@/i18n/I18nContext';
import { useLiveQuery } from 'dexie-react-hooks';
import { db } from '@/lib/db';

interface TagSelectorProps {
    category: TagCategory;
    selectedTagIds: string[];
    onToggleTag: (tagId: string) => void;
    label?: string;
    suggestedTagNames?: string[];
    suggestedCustomTagNames?: string[];
}

export default function TagSelector({ category, selectedTagIds, onToggleTag, label, suggestedTagNames, suggestedCustomTagNames }: TagSelectorProps) {
    const { t } = useI18n();
    const [search, setSearch] = useState('');
    const [isCreating, setIsCreating] = useState(false);
    const [creatingSuggestion, setCreatingSuggestion] = useState<string | null>(null);

    const tags = useLiveQuery(
        () => db.cache_tags.where('category').equals(category).sortBy('popularity_score'),
        [category],
        []
    );

    const isLoading = tags === undefined;

    const filteredTags = useMemo(() => {
        const tagList = tags || [];
        if (!search) return tagList;
        const s = search.toLowerCase();
        return tagList.filter((tag) => {
            const rawMatch = tag.name.toLowerCase().includes(s);
            const translatedMatch = tag.is_system_default && t(`aroma.${tag.name}`).toLowerCase().includes(s);
            return rawMatch || translatedMatch;
        });
    }, [tags, search, t]);

    const handleCreateTag = async () => {
        if (!search || isCreating) return;

        setIsCreating(true);
        const result = await createCustomTag(search, category);
        if (result.success && result.tag) {
            await db.cache_tags.put(result.tag!);
            onToggleTag(result.tag!.id);
            setSearch('');
        }
        setIsCreating(false);
    };

    const selectedTags = (tags || []).filter(t => selectedTagIds.includes(t.id));

    return (
        <div className="space-y-3">
            {label && (
                <label className="text-[11px] font-black text-zinc-400 uppercase tracking-widest block">{label}</label>
            )}

            {/* Selected Tags */}
            <div className="flex flex-wrap gap-2 min-h-[32px]">
                {selectedTags.length > 0 ? (
                    selectedTags.map(tag => (
                        <button
                            key={tag.id}
                            type="button"
                            onClick={() => onToggleTag(tag.id)}
                            className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-amber-600 text-white rounded-full text-[10px] font-black uppercase tracking-tight shadow-sm shadow-amber-600/20 animate-in fade-in zoom-in-95"
                        >
                            {tag.is_system_default ? t(`aroma.${tag.name}`) : tag.name}
                            <X size={12} />
                        </button>
                    ))
                ) : (
                    <span className="text-[10px] italic text-zinc-400 font-medium">Noch keine Tags gewählt...</span>
                )}
            </div>

            {/* Search and Suggest */}
            <div className="relative">
                <div className="relative flex items-center">
                    <Search className="absolute left-3 text-zinc-400" size={14} />
                    <input
                        type="text"
                        value={search}
                        onChange={(e) => setSearch(e.target.value)}
                        placeholder="Tag suchen oder hinzufügen..."
                        className="w-full pl-9 pr-4 py-2 bg-zinc-50 dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded-xl text-xs focus:ring-2 focus:ring-amber-500 outline-none transition-all dark:text-zinc-200 placeholder:text-zinc-400"
                    />
                    {isCreating && (
                        <Loader2 className="absolute right-3 animate-spin text-amber-600" size={14} />
                    )}
                </div>

                {search && (
                    <div className="absolute z-10 w-full mt-2 bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded-2xl shadow-xl overflow-hidden animate-in fade-in slide-in-from-top-2">
                        <div className="max-h-48 overflow-y-auto">
                            {filteredTags.length > 0 ? (
                                filteredTags.map(tag => (
                                    <button
                                        key={tag.id}
                                        type="button"
                                        onClick={() => {
                                            onToggleTag(tag.id);
                                            setSearch('');
                                        }}
                                        className="w-full px-4 py-2.5 text-left text-xs font-bold text-zinc-700 dark:text-zinc-300 hover:bg-zinc-50 dark:hover:bg-zinc-700/50 flex items-center justify-between border-b border-zinc-100 dark:border-zinc-700 last:border-0"
                                    >
                                        {tag.is_system_default ? t(`aroma.${tag.name}`) : tag.name}
                                        {selectedTagIds.includes(tag.id) && <Check size={12} className="text-amber-600" />}
                                    </button>
                                ))
                            ) : (
                                <button
                                    type="button"
                                    onClick={handleCreateTag}
                                    className="w-full px-4 py-3 text-left text-xs font-bold text-amber-600 hover:bg-amber-50 dark:hover:bg-amber-900/10 flex items-center gap-2"
                                >
                                    <Plus size={14} />
                                    "{search}" als neuen Tag hinzufügen
                                </button>
                            )}
                        </div>
                    </div>
                )}
            </div>

            {/* AI Suggestions */}
            {!search && suggestedTagNames && suggestedTagNames.length > 0 && (
                <div className="space-y-2">
                    <div className="flex items-center gap-1.5 text-[9px] font-black uppercase tracking-widest text-amber-500">
                        <Sparkles size={10} /> {t('camera.wbMatchFound') ? 'KI Vorschläge' : 'AI Suggestions'}
                    </div>
                    <div className="flex flex-wrap gap-1.5">
                        {(tags || [])
                            .filter(t => !selectedTagIds.includes(t.id) && suggestedTagNames.some((s: string) => s.toLowerCase() === t.name.toLowerCase()))
                            .map(tag => (
                                <button
                                    key={tag.id}
                                    type="button"
                                    onClick={() => onToggleTag(tag.id)}
                                    className="px-2.5 py-1 rounded-lg bg-amber-50 dark:bg-amber-900/20 text-amber-600 dark:text-amber-400 text-[10px] font-bold uppercase tracking-tight hover:bg-amber-100 dark:hover:bg-amber-900/30 transition-colors border border-amber-200 dark:border-amber-800/50 flex items-center gap-1.5"
                                >
                                    <Sparkles size={10} />
                                    {tag.is_system_default ? t(`aroma.${tag.name}`) : tag.name}
                                </button>
                            ))}
                    </div>
                </div>
            )}

            {/* AI Custom Suggestions */}
            {!search && suggestedCustomTagNames && suggestedCustomTagNames.length > 0 && (
                <div className="space-y-2">
                    <div className="flex items-center gap-1.5 text-[9px] font-black uppercase tracking-widest text-zinc-400">
                        Dominante Note anlegen?
                    </div>
                    <div className="flex flex-wrap gap-1.5">
                        {suggestedCustomTagNames
                            .filter(name => !(tags || []).some(t => t.name.toLowerCase() === name.toLowerCase()))
                            .map(name => (
                                <button
                                    key={name}
                                    type="button"
                                    disabled={creatingSuggestion === name}
                                    onClick={async () => {
                                        setCreatingSuggestion(name);
                                        const result = await createCustomTag(name, category);
                                        if (result.success && result.tag) {
                                            await db.cache_tags.put(result.tag!);
                                            onToggleTag(result.tag!.id);
                                        }
                                        setCreatingSuggestion(null);
                                    }}
                                    className="px-2.5 py-1 rounded-lg bg-zinc-50 dark:bg-zinc-800/50 text-zinc-500 dark:text-zinc-400 text-[10px] font-bold uppercase tracking-tight hover:bg-amber-600 hover:text-white transition-all border border-dashed border-zinc-200 dark:border-zinc-700/50 flex items-center gap-1.5 disabled:opacity-50"
                                >
                                    {creatingSuggestion === name ? <Loader2 size={10} className="animate-spin" /> : <Plus size={10} />}
                                    {name}
                                </button>
                            ))}
                    </div>
                </div>
            )}

            {/* Suggestions Chips (limit to 6 random or most common) */}
            {!search && tags.length > 0 && (
                <div className="flex flex-wrap gap-1.5 pt-1">
                    {(tags || [])
                        .filter(t => !selectedTagIds.includes(t.id) && (!suggestedTagNames || !suggestedTagNames.some((s: string) => s.toLowerCase() === t.name.toLowerCase())))
                        .slice(0, 8)
                        .map(tag => (
                            <button
                                key={tag.id}
                                type="button"
                                onClick={() => onToggleTag(tag.id)}
                                className="px-2.5 py-1 rounded-lg bg-zinc-100 dark:bg-zinc-800 text-zinc-500 dark:text-zinc-400 text-[10px] font-bold uppercase tracking-tight hover:bg-zinc-200 dark:hover:bg-zinc-700 hover:text-zinc-700 dark:hover:text-zinc-200 transition-colors border border-zinc-200/50 dark:border-zinc-700/50"
                            >
                                {tag.is_system_default ? t(`aroma.${tag.name}`) : tag.name}
                            </button>
                        ))}
                </div>
            )}
        </div>
    );
}
