'use client';

import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { ChevronDown, Wind, Utensils, Droplets, Sparkles, Send, Users, Star, AlertTriangle, Check, Zap } from 'lucide-react';
import { BottleMetadata } from '@/types/whisky';
import TagSelector from './TagSelector';
import { useLiveQuery } from 'dexie-react-hooks';
import { db } from '@/lib/db';
import { createClient } from '@/lib/supabase/client';
import { useI18n } from '@/i18n/I18nContext';

interface TastingEditorProps {
    bottleMetadata: BottleMetadata;
    image: string | null;
    onSave: (data: any) => void;
    onOpenSessions: () => void;
    activeSessionName?: string;
    activeSessionId?: string;
}

export default function TastingEditor({ bottleMetadata, image, onSave, onOpenSessions, activeSessionName, activeSessionId }: TastingEditorProps) {
    const { t } = useI18n();
    const supabase = createClient();
    const [rating, setRating] = useState(85);
    const [noseNotes, setNoseNotes] = useState('');
    const [palateNotes, setPalateNotes] = useState('');
    const [finishNotes, setFinishNotes] = useState('');
    const [isSample, setIsSample] = useState(false);

    // Sliders for evaluation
    const [noseScore, setNoseScore] = useState(50);
    const [tasteScore, setTasteScore] = useState(50);
    const [finishScore, setFinishScore] = useState(50);
    const [complexityScore, setComplexityScore] = useState(75);
    const [balanceScore, setBalanceScore] = useState(85);

    const [noseTagIds, setNoseTagIds] = useState<string[]>([]);
    const [palateTagIds, setPalateTagIds] = useState<string[]>([]);
    const [finishTagIds, setFinishTagIds] = useState<string[]>([]);
    const [textureTagIds, setTextureTagIds] = useState<string[]>([]);
    const [selectedBuddyIds, setSelectedBuddyIds] = useState<string[]>([]);

    const buddies = useLiveQuery(() => db.cache_buddies.toArray(), [], [] as any[]);
    const [lastDramInSession, setLastDramInSession] = useState<{ name: string; isSmoky: boolean; timestamp: number } | null>(null);
    const [showPaletteWarning, setShowPaletteWarning] = useState(false);

    const suggestedTags = bottleMetadata.suggested_tags || [];
    const suggestedCustomTags = bottleMetadata.suggested_custom_tags || [];

    // Session-based pre-fill and Palette Checker
    useEffect(() => {
        const fetchSessionData = async () => {
            if (activeSessionId) {
                const { data: participants } = await supabase
                    .from('session_participants')
                    .select('buddy_id')
                    .eq('session_id', activeSessionId);

                if (participants) {
                    setSelectedBuddyIds(participants.map(p => p.buddy_id));
                }

                const { data: lastTastings } = await supabase
                    .from('tastings')
                    .select(`
                        id,
                        tasted_at,
                        bottles(name, category),
                        tasting_tags(tags(name))
                    `)
                    .eq('session_id', activeSessionId)
                    .order('tasted_at', { ascending: false })
                    .limit(1);

                if (lastTastings && lastTastings.length > 0) {
                    const last = lastTastings[0];
                    const tags = (last as any).tasting_tags?.map((t: any) => t.tags.name) || [];
                    const category = (last as any).bottles?.category || '';
                    const text = (tags.join(' ') + ' ' + category).toLowerCase();
                    const smokyKeywords = ['rauch', 'torf', 'smoke', 'peat', 'islay', 'ash', 'lagerfeuer'];
                    const isSmoky = smokyKeywords.some(kw => text.includes(kw));

                    setLastDramInSession({
                        name: (last as any).bottles?.name || 'Unbekannt',
                        isSmoky,
                        timestamp: new Date(last.tasted_at).getTime()
                    });
                }
            }
        };
        fetchSessionData();
    }, [activeSessionId, supabase]);

    useEffect(() => {
        if (lastDramInSession?.isSmoky) {
            const now = Date.now();
            const diffMin = (now - lastDramInSession.timestamp) / (1000 * 60);
            if (diffMin < 20) setShowPaletteWarning(true);
        }
    }, [lastDramInSession]);

    const toggleBuddy = (id: string) => {
        setSelectedBuddyIds(prev => prev.includes(id) ? prev.filter(bid => bid !== id) : [...prev, id]);
    };

    const handleInternalSave = () => {
        onSave({
            rating,
            nose_notes: noseNotes,
            palate_notes: palateNotes,
            finish_notes: finishNotes,
            is_sample: isSample,
            buddy_ids: selectedBuddyIds,
            tag_ids: [...noseTagIds, ...palateTagIds, ...finishTagIds, ...textureTagIds],
            // Visual data for ResultCard
            nose: noseScore,
            taste: tasteScore,
            finish: finishScore,
            complexity: complexityScore,
            balance: balanceScore
        });
    };

    return (
        <div className="flex-1 flex flex-col w-full bg-[#0F1014] h-full overflow-hidden">
            {/* Top Context Bar - Flex Child 1 */}
            <button
                onClick={onOpenSessions}
                className="w-full p-6 bg-black/40 backdrop-blur-md border-b border-white/10 flex items-center justify-between group shrink-0"
            >
                <div className="text-left">
                    <p className="text-[10px] font-black uppercase tracking-widest text-amber-500">Kontext</p>
                    <p className="font-bold text-white leading-none mt-1">{activeSessionName || 'Trinkst du in Gesellschaft?'}</p>
                </div>
                <ChevronDown size={20} className="text-amber-500 group-hover:translate-y-1 transition-transform" />
            </button>

            {/* Main Scrollable Content - Flex Child 2 */}
            <div className="flex-1 overflow-y-auto overflow-x-hidden px-6 py-8 space-y-12">
                {/* Palette Warning */}
                {showPaletteWarning && (
                    <motion.div
                        initial={{ opacity: 0, y: -20 }}
                        animate={{ opacity: 1, y: 0 }}
                        className="p-5 bg-amber-500/10 border border-amber-500/20 rounded-3xl flex items-start gap-3"
                    >
                        <AlertTriangle size={24} className="text-amber-500 shrink-0 mt-0.5" />
                        <div className="space-y-1">
                            <p className="text-[10px] font-black uppercase tracking-wider text-amber-500">Palette-Checker</p>
                            <p className="text-xs font-bold text-white leading-relaxed">
                                Dein letzter Dram "{lastDramInSession?.name}" war torfig. Trink etwas Wasser!
                            </p>
                            <button onClick={() => setShowPaletteWarning(false)} className="text-[10px] font-black uppercase text-amber-500 underline mt-2 block">Verstanden</button>
                        </div>
                    </motion.div>
                )}

                {/* Hero Section */}
                <div className="flex items-center gap-6">
                    <div className="w-24 h-32 bg-white/5 rounded-2xl border border-white/10 flex items-center justify-center overflow-hidden shrink-0 shadow-2xl relative">
                        {image ? (
                            <img src={image} alt="Bottle Preview" className="w-full h-full object-cover" />
                        ) : (
                            <div className="text-[10px] text-white/20 uppercase font-black rotate-[-15deg]">No Photo</div>
                        )}
                    </div>
                    <div className="flex-1 min-w-0">
                        <h1 className="text-3xl font-black text-amber-600 mb-1 truncate leading-none uppercase tracking-tight">
                            {bottleMetadata.distillery || 'Destillerie'}
                        </h1>
                        <p className="text-white text-xl font-bold truncate mb-2">{bottleMetadata.name || 'Unbekannter Malt'}</p>
                        <p className="text-white/40 text-[10px] font-black uppercase tracking-widest leading-none">
                            {bottleMetadata.category || 'Whisky'} {bottleMetadata.abv ? `• ${bottleMetadata.abv}%` : ''} {bottleMetadata.age ? `• ${bottleMetadata.age}y` : ''}
                        </p>
                    </div>
                </div>

                {/* Rating Slider */}
                <div className="space-y-6 bg-white/5 p-8 rounded-[40px] border border-white/10 shadow-inner relative overflow-hidden">
                    <div className="absolute top-0 right-0 p-4 opacity-5 pointer-events-none">
                        <Zap size={120} className="text-amber-500" />
                    </div>
                    <div className="flex items-center justify-between relative z-10">
                        <label className="text-xs font-black text-white/40 uppercase tracking-[0.2em] flex items-center gap-2">
                            <Star size={14} className="text-amber-500 fill-amber-500" />
                            {t('tasting.rating')}
                        </label>
                        <span className="text-4xl font-black text-amber-600 tracking-tighter">{rating}<span className="text-white/20 text-sm ml-1">/100</span></span>
                    </div>
                    <input
                        type="range"
                        min="0"
                        max="100"
                        value={rating}
                        onChange={(e) => setRating(parseInt(e.target.value))}
                        className="w-full h-2 bg-zinc-800 rounded-full appearance-none cursor-pointer accent-amber-600 transition-all"
                    />
                    <div className="flex justify-between text-[10px] text-zinc-500 font-black uppercase tracking-widest px-1 relative z-10">
                        <span>Swill</span>
                        <span>Dram</span>
                        <span>Legendary</span>
                    </div>

                    <div className="flex gap-3 pt-2 relative z-10">
                        {['Bottle', 'Sample'].map(type => (
                            <button
                                key={type}
                                onClick={() => setIsSample(type === 'Sample')}
                                className={`flex-1 py-4 rounded-2xl text-[10px] font-black uppercase tracking-widest border transition-all ${(type === 'Sample' ? isSample : !isSample)
                                        ? 'bg-zinc-100 border-zinc-100 text-zinc-900 shadow-lg'
                                        : 'bg-transparent border-white/10 text-white/40 hover:border-white/30'
                                    }`}
                            >
                                {type}
                            </button>
                        ))}
                    </div>
                </div>

                {/* Evaluation Sliders Area */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                    <CustomSlider label="Complexity" value={complexityScore} onChange={setComplexityScore} icon={<Sparkles size={18} />} />
                    <CustomSlider label="Balance" value={balanceScore} onChange={setBalanceScore} icon={<Check size={18} />} />
                </div>

                {/* Sections */}
                <div className="space-y-12 pb-12">
                    {/* Nose Section */}
                    <div className="space-y-8 bg-zinc-900/50 p-8 rounded-[40px] border border-white/5">
                        <div className="flex items-center gap-5">
                            <div className="w-14 h-14 rounded-3xl bg-amber-500/10 flex items-center justify-center text-amber-500 shrink-0 border border-amber-500/20 shadow-xl">
                                <Wind size={28} />
                            </div>
                            <div>
                                <h3 className="text-xl font-black text-white uppercase tracking-widest leading-none">{t('tasting.nose')}</h3>
                                <p className="text-[10px] text-white/30 font-black uppercase tracking-widest mt-2 px-0.5">Aroma & Bouquet</p>
                            </div>
                        </div>

                        <div className="space-y-6">
                            <CustomSlider label="Nose Intensity" value={noseScore} onChange={setNoseScore} icon={<Sparkles size={16} />} />

                            <div className="space-y-3">
                                <p className="text-[10px] font-black text-white/20 uppercase tracking-widest px-1">Tags</p>
                                <TagSelector
                                    category="nose"
                                    selectedTagIds={noseTagIds}
                                    onToggleTag={(id) => setNoseTagIds(prev => prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id])}
                                    suggestedTagNames={suggestedTags}
                                    suggestedCustomTagNames={suggestedCustomTags}
                                />
                            </div>
                            <div className="space-y-3">
                                <p className="text-[10px] font-black text-white/20 uppercase tracking-widest px-1">Eigene Notizen</p>
                                <textarea
                                    value={noseNotes}
                                    onChange={(e) => setNoseNotes(e.target.value)}
                                    placeholder={t('tasting.notesPlaceholder') || "Wie riecht er?..."}
                                    className="w-full p-6 bg-zinc-900 border-none rounded-3xl text-sm text-zinc-200 focus:ring-2 focus:ring-amber-500 outline-none min-h-[120px] resize-none transition-all placeholder:text-zinc-600 shadow-inner"
                                />
                            </div>
                        </div>
                    </div>

                    {/* Palate Section */}
                    <div className="space-y-8 bg-zinc-900/50 p-8 rounded-[40px] border border-white/5">
                        <div className="flex items-center gap-5">
                            <div className="w-14 h-14 rounded-3xl bg-amber-500/10 flex items-center justify-center text-amber-500 shrink-0 border border-amber-500/20 shadow-xl">
                                <Utensils size={28} />
                            </div>
                            <div>
                                <h3 className="text-xl font-black text-white uppercase tracking-widest leading-none">{t('tasting.palate')}</h3>
                                <p className="text-[10px] text-white/30 font-black uppercase tracking-widest mt-2 px-0.5">Geschmack & Textur</p>
                            </div>
                        </div>

                        <div className="space-y-6">
                            <CustomSlider label="Taste Impact" value={tasteScore} onChange={setTasteScore} icon={<Sparkles size={16} />} />

                            <div className="space-y-3">
                                <p className="text-[10px] font-black text-white/20 uppercase tracking-widest px-1">Tags</p>
                                <TagSelector
                                    category="taste"
                                    selectedTagIds={palateTagIds}
                                    onToggleTag={(id) => setPalateTagIds(prev => prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id])}
                                    suggestedTagNames={suggestedTags}
                                    suggestedCustomTagNames={suggestedCustomTags}
                                />
                            </div>
                            <div className="space-y-3">
                                <p className="text-[10px] font-black text-white/20 uppercase tracking-widest px-1">Eigene Notizen</p>
                                <textarea
                                    value={palateNotes}
                                    onChange={(e) => setPalateNotes(e.target.value)}
                                    placeholder={t('tasting.notesPlaceholder') || "Wie schmeckt er?..."}
                                    className="w-full p-6 bg-zinc-900 border-none rounded-3xl text-sm text-zinc-200 focus:ring-2 focus:ring-amber-500 outline-none min-h-[120px] resize-none transition-all placeholder:text-zinc-600 shadow-inner"
                                />
                            </div>
                        </div>
                    </div>

                    {/* Finish Section */}
                    <div className="space-y-8 bg-zinc-900/50 p-8 rounded-[40px] border border-white/5">
                        <div className="flex items-center gap-5">
                            <div className="w-14 h-14 rounded-3xl bg-amber-500/10 flex items-center justify-center text-amber-500 shrink-0 border border-amber-500/20 shadow-xl">
                                <Droplets size={28} />
                            </div>
                            <div>
                                <h3 className="text-xl font-black text-white uppercase tracking-widest leading-none">{t('tasting.finish')}</h3>
                                <p className="text-[10px] text-white/30 font-black uppercase tracking-widest mt-2 px-0.5">Abgang & Nachklang</p>
                            </div>
                        </div>

                        <div className="space-y-6">
                            <CustomSlider label="Finish Duration" value={finishScore} onChange={setFinishScore} icon={<Sparkles size={16} />} />

                            <div className="space-y-6 pt-4 border-t border-white/5">
                                <div className="space-y-3">
                                    <p className="text-[10px] font-black text-white/20 uppercase tracking-widest px-1">Aroma Tags</p>
                                    <TagSelector
                                        category="finish"
                                        selectedTagIds={finishTagIds}
                                        onToggleTag={(id) => setFinishTagIds(prev => prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id])}
                                        suggestedTagNames={suggestedTags}
                                        suggestedCustomTagNames={suggestedCustomTags}
                                    />
                                </div>
                                <div className="space-y-3">
                                    <p className="text-[10px] font-black text-white/20 uppercase tracking-widest px-1">Gefühl & Textur</p>
                                    <TagSelector
                                        category="texture"
                                        selectedTagIds={textureTagIds}
                                        onToggleTag={(id) => setTextureTagIds(prev => prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id])}
                                        suggestedTagNames={suggestedTags}
                                        suggestedCustomTagNames={suggestedCustomTags}
                                    />
                                </div>
                            </div>
                            <div className="space-y-3">
                                <p className="text-[10px] font-black text-white/20 uppercase tracking-widest px-1">Eigene Notizen</p>
                                <textarea
                                    value={finishNotes}
                                    onChange={(e) => setFinishNotes(e.target.value)}
                                    placeholder={t('tasting.notesPlaceholder') || "Der bleibende Eindruck..."}
                                    className="w-full p-6 bg-zinc-900 border-none rounded-3xl text-sm text-zinc-200 focus:ring-2 focus:ring-amber-500 outline-none min-h-[120px] resize-none transition-all placeholder:text-zinc-600 shadow-inner"
                                />
                            </div>
                        </div>
                    </div>

                    {/* Buddy Selection */}
                    {buddies && buddies.length > 0 && (
                        <div className="space-y-8 bg-zinc-900/50 p-8 rounded-[40px] border border-white/5">
                            <div className="flex items-center gap-5">
                                <div className="w-14 h-14 rounded-3xl bg-amber-500/10 flex items-center justify-center text-amber-500 shrink-0 border border-amber-500/20 shadow-xl">
                                    <Users size={28} />
                                </div>
                                <div>
                                    <h3 className="text-xl font-black text-white uppercase tracking-widest leading-none">Mit wem trinkst du?</h3>
                                    <p className="text-[10px] text-white/30 font-black uppercase tracking-widest mt-2 px-0.5">Gesellschaft & Buddies</p>
                                </div>
                            </div>
                            <div className="flex flex-wrap gap-2">
                                {buddies.map(buddy => (
                                    <button
                                        key={buddy.id}
                                        onClick={() => toggleBuddy(buddy.id)}
                                        className={`px-5 py-3 rounded-2xl text-[10px] font-black uppercase transition-all border flex items-center gap-2 ${selectedBuddyIds.includes(buddy.id)
                                                ? 'bg-amber-600 border-amber-600 text-white shadow-lg'
                                                : 'bg-transparent border-white/10 text-white/40 hover:border-white/30'
                                            }`}
                                    >
                                        {selectedBuddyIds.includes(buddy.id) && <Check size={14} />}
                                        {buddy.name}
                                    </button>
                                ))}
                            </div>
                        </div>
                    )}
                </div>
            </div>

            {/* Sticky Footer - Flex Child 3 */}
            <div className="w-full p-8 bg-black/60 backdrop-blur-xl border-t border-white/10 shrink-0">
                <button
                    onClick={handleInternalSave}
                    className="w-full py-5 bg-amber-600 text-white rounded-3xl font-black uppercase tracking-widest text-xs flex items-center justify-center gap-4 shadow-xl active:scale-[0.98] transition-all"
                >
                    <Send size={20} />
                    {t('tasting.saveTasting')}
                    <div className="ml-auto bg-black/20 px-3 py-1 rounded-full text-[10px] font-black text-amber-200">{rating}</div>
                </button>
            </div>
        </div>
    );
}

function CustomSlider({ label, value, onChange, icon }: any) {
    return (
        <div className="space-y-4 bg-zinc-900/50 p-6 rounded-3xl border border-white/5 shadow-inner">
            <div className="flex items-center justify-between">
                <div className="flex items-center gap-3 text-white/40">
                    <div className="p-2 rounded-xl bg-amber-500/10 text-amber-500">
                        {icon}
                    </div>
                    <span className="text-[10px] font-black uppercase tracking-[0.2em]">{label}</span>
                </div>
                <span className="text-2xl font-black text-amber-600 tracking-tighter">{value}</span>
            </div>
            <input
                type="range"
                min="0"
                max="100"
                value={value}
                onChange={(e) => onChange(parseInt(e.target.value))}
                className="w-full h-1.5 bg-zinc-800 rounded-full appearance-none cursor-pointer accent-amber-600 transition-all"
            />
        </div>
    );
}
