'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[];
    isLoading?: boolean;
}

export default function TagSelector({ category, selectedTagIds, onToggleTag, label, suggestedTagNames, suggestedCustomTagNames, isLoading }: 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 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-4">
            {label && (
                <label className="text-[10px] font-black text-zinc-500 uppercase tracking-[0.15em] 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-orange-600 text-white rounded-xl text-[10px] font-black uppercase tracking-tight shadow-lg shadow-orange-950/20 animate-in fade-in zoom-in-95 hover:bg-orange-500 transition-colors"
                        >
                            {tag.is_system_default ? t(`aroma.${tag.name}`) : tag.name}
                            <X size={12} strokeWidth={3} />
                        </button>
                    ))
                ) : (
                    <span className="text-[10px] italic text-zinc-600 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.5 text-zinc-500" size={14} />
                    <input
                        type="text"
                        value={search}
                        onChange={(e) => setSearch(e.target.value)}
                        placeholder="Tag suchen oder hinzufügen..."
                        className="w-full pl-10 pr-4 py-3 bg-zinc-950 border border-zinc-800 rounded-2xl text-[11px] font-medium focus:ring-1 focus:ring-orange-600/50 focus:border-orange-600/50 outline-none transition-all text-zinc-200 placeholder:text-zinc-600"
                    />
                    {isCreating && (
                        <Loader2 className="absolute right-3.5 animate-spin text-orange-600" size={14} />
                    )}
                </div>

                {search && (
                    <div className="absolute z-50 w-full mt-2 bg-zinc-950 border border-zinc-800 rounded-2xl shadow-2xl overflow-hidden animate-in fade-in slide-in-from-top-2">
                        <div className="max-h-60 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-3 text-left text-[11px] font-bold text-zinc-300 hover:bg-zinc-900 flex items-center justify-between border-b border-zinc-900 last:border-0 transition-colors"
                                    >
                                        {tag.is_system_default ? t(`aroma.${tag.name}`) : tag.name}
                                        {selectedTagIds.includes(tag.id) && <Check size={12} className="text-orange-600" strokeWidth={3} />}
                                    </button>
                                ))
                            ) : (
                                <button
                                    type="button"
                                    onClick={handleCreateTag}
                                    className="w-full px-4 py-4 text-left text-[11px] font-bold text-orange-500 hover:bg-orange-500/5 flex items-center gap-2 transition-colors"
                                >
                                    <Plus size={14} strokeWidth={3} />
                                    "{search}" als neuen Tag hinzufügen
                                </button>
                            )}
                        </div>
                    </div>
                )}
            </div>

            {/* AI Suggestions */}
            {!search && (isLoading || (suggestedTagNames && suggestedTagNames.length > 0)) && (
                <div className="space-y-2 py-1">
                    <div className="flex items-center gap-1.5 text-[9px] font-black uppercase tracking-[0.2em] text-orange-600">
                        {isLoading ? <Loader2 size={10} className="animate-spin" /> : <Sparkles size={10} className="fill-orange-600/20" />}
                        {isLoading ? 'Analysiere Aromen...' : 'KI Vorschläge'}
                    </div>
                    <div className="flex flex-wrap gap-2">
                        {isLoading ? (
                            [1, 2, 3].map(i => (
                                <div key={i} className="h-7 w-16 bg-zinc-900 animate-pulse rounded-xl" />
                            ))
                        ) : (
                            (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-3 py-1.5 rounded-xl bg-orange-950/20 text-orange-500 text-[10px] font-black uppercase tracking-tight hover:bg-orange-600 hover:text-white transition-all border border-orange-600/20 flex items-center gap-1.5 shadow-sm"
                                    >
                                        <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 py-1">
                    <div className="flex items-center gap-1.5 text-[9px] font-black uppercase tracking-[0.2em] text-zinc-500">
                        Dominante Note anlegen?
                    </div>
                    <div className="flex flex-wrap gap-2">
                        {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-3 py-1.5 rounded-xl bg-zinc-950/50 text-zinc-500 text-[10px] font-black uppercase tracking-tight hover:bg-zinc-800 hover:text-zinc-200 transition-all border border-dashed border-zinc-800 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 */}
            {!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.5 rounded-xl bg-zinc-900 text-zinc-500 text-[10px] font-bold uppercase tracking-tight hover:bg-zinc-800 hover:text-zinc-300 transition-colors border border-zinc-800/50"
                            >
                                {tag.is_system_default ? t(`aroma.${tag.name}`) : tag.name}
                            </button>
                        ))}
                </div>
            )}
        </div>
    );
}
