'use client';

import React, { useState, useEffect } from 'react';
import { saveTasting } from '@/services/save-tasting';
import { Loader2, Send, Star, Users, Check, Sparkles, Droplets, Wind, Utensils, Zap } from 'lucide-react';
import { createClient } from '@/lib/supabase/client';
import { useI18n } from '@/i18n/I18nContext';
import { useSession } from '@/context/SessionContext';
import TagSelector from './TagSelector';
import { useLiveQuery } from 'dexie-react-hooks';
import { db } from '@/lib/db';
import { AlertTriangle } from 'lucide-react';

interface Buddy {
    id: string;
    name: string;
}

interface TastingNoteFormProps {
    bottleId?: string; // Real ID
    pendingBottleId?: string; // Temp ID for queued scans
    sessionId?: string;
    onSuccess?: () => void;
}

export default function TastingNoteForm({ bottleId, pendingBottleId, sessionId, onSuccess }: TastingNoteFormProps) {
    const { t } = useI18n();
    const supabase = createClient();
    const [rating, setRating] = useState(85);
    const [nose, setNose] = useState('');
    const [palate, setPalate] = useState('');
    const [finish, setFinish] = useState('');
    const [isSample, setIsSample] = useState(false);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const buddies = useLiveQuery(() => db.cache_buddies.toArray(), [], [] as Buddy[]);
    const [selectedBuddyIds, setSelectedBuddyIds] = useState<string[]>([]);
    const [noseTagIds, setNoseTagIds] = useState<string[]>([]);
    const [palateTagIds, setPalateTagIds] = useState<string[]>([]);
    const [finishTagIds, setFinishTagIds] = useState<string[]>([]);
    const [suggestedTags, setSuggestedTags] = useState<string[]>([]);
    const [suggestedCustomTags, setSuggestedCustomTags] = useState<string[]>([]);
    const { activeSession } = useSession();
    const [lastDramInSession, setLastDramInSession] = useState<{ name: string; isSmoky: boolean; timestamp: number } | null>(null);
    const [showPaletteWarning, setShowPaletteWarning] = useState(false);

    const effectiveSessionId = sessionId || activeSession?.id;

    useEffect(() => {
        const fetchData = async () => {
            if (!bottleId) return;

            // Fetch Bottle Suggestions
            const { data: bottleData } = await supabase
                .from('bottles')
                .select('suggested_tags, suggested_custom_tags')
                .eq('id', bottleId)
                .maybeSingle();

            if (bottleData?.suggested_tags) {
                setSuggestedTags(bottleData.suggested_tags);
            }
            if (bottleData?.suggested_custom_tags) {
                setSuggestedCustomTags(bottleData.suggested_custom_tags);
            }

            // If Session ID, fetch session participants and pre-select them, and fetch last dram
            if (effectiveSessionId) {
                const { data: participants } = await supabase
                    .from('session_participants')
                    .select('buddy_id')
                    .eq('session_id', effectiveSessionId);

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

                // Fetch last dram for Palette Checker (Only online)
                if (navigator.onLine) {
                    const { data: lastTastings } = await supabase
                        .from('tastings')
                        .select(`
                            id,
                            tasted_at,
                            bottles(name, category),
                            tasting_tags(tags(name))
                        `)
                        .eq('session_id', effectiveSessionId)
                        .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()
                        });
                    }
                }
            } else {
                setSelectedBuddyIds([]);
                setLastDramInSession(null);
            }
        };
        fetchData();
    }, [supabase, effectiveSessionId, bottleId]);

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

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

    const toggleNoseTag = (id: string) => {
        setNoseTagIds(prev => prev.includes(id) ? prev.filter(tid => tid !== id) : [...prev, id]);
    };

    const togglePalateTag = (id: string) => {
        setPalateTagIds(prev => prev.includes(id) ? prev.filter(tid => tid !== id) : [...prev, id]);
    };

    const toggleFinishTag = (id: string) => {
        setFinishTagIds(prev => prev.includes(id) ? prev.filter(tid => tid !== id) : [...prev, id]);
    };

    const clearForm = () => {
        setNose('');
        setPalate('');
        setFinish('');
        setSelectedBuddyIds([]);
        setNoseTagIds([]);
        setPalateTagIds([]);
        setFinishTagIds([]);
        setError(null);
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setLoading(true);
        setError(null);

        const data = {
            bottle_id: bottleId as string,
            session_id: effectiveSessionId,
            rating,
            nose_notes: nose,
            palate_notes: palate,
            finish_notes: finish,
            is_sample: isSample,
            buddy_ids: selectedBuddyIds,
            tag_ids: [...noseTagIds, ...palateTagIds, ...finishTagIds],
        };

        try {
            if (!navigator.onLine || pendingBottleId) {
                // Save to Offline DB
                await db.pending_tastings.add({
                    bottle_id: bottleId,
                    pending_bottle_id: pendingBottleId,
                    data,
                    tasted_at: new Date().toISOString()
                });
                clearForm();
                setLoading(false);
                onSuccess?.();
                return;
            }

            const result = await saveTasting(data);

            if (result.success) {
                clearForm();
                onSuccess?.();
            } else {
                setError(result.error || t('common.error'));
            }
        } catch (err) {
            setError(t('common.error'));
        } finally {
            setLoading(false);
        }
    };

    return (
        <form onSubmit={handleSubmit} className="space-y-6">
            {activeSession && (
                <div className="p-3 bg-amber-50 dark:bg-amber-900/10 border border-amber-200 dark:border-amber-900/30 rounded-2xl flex items-center gap-3 animate-in fade-in slide-in-from-top-2">
                    <div className="bg-amber-600 text-white p-2 rounded-xl">
                        <Sparkles size={16} />
                    </div>
                    <div className="min-w-0">
                        <p className="text-[10px] font-black uppercase tracking-wider text-amber-700 dark:text-amber-400">Recording for Session</p>
                        <p className="text-xs font-bold text-amber-900 dark:text-amber-200 truncate">{activeSession.name}</p>
                    </div>
                </div>
            )}

            {showPaletteWarning && (
                <div className="p-4 bg-amber-500/10 border border-amber-500/20 rounded-2xl flex items-start gap-3 animate-in fade-in slide-in-from-top-2">
                    <AlertTriangle size={20} 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-600">Palette-Checker Warnung</p>
                        <p className="text-xs font-bold text-amber-900 dark:text-amber-200">
                            Dein letzter Dram war "{lastDramInSession?.name}".
                        </p>
                        <p className="text-[10px] text-amber-800/80 dark:text-amber-400/80 leading-relaxed font-medium">
                            Da er sehr torfig war und erst vor Kurzem verkostet wurde, könnten deine Geschmacksnerven noch beeinträchtigt sein. Trink am besten etwas Wasser!
                        </p>
                        <button
                            type="button"
                            onClick={() => setShowPaletteWarning(false)}
                            className="text-[9px] font-black uppercase text-amber-600 underline"
                        >
                            Ignorieren
                        </button>
                    </div>
                </div>
            )}

            <div className="space-y-4">
                <div className="flex items-center justify-between">
                    <label className="text-[11px] font-black text-zinc-400 uppercase tracking-widest flex items-center gap-2">
                        <Star size={14} className="text-amber-500 fill-amber-500" />
                        {t('tasting.rating')}
                    </label>
                    <span className="text-2xl font-black text-amber-600 tracking-tighter">{rating}<span className="text-zinc-400 text-sm ml-0.5 font-bold">/100</span></span>
                </div>
                <input
                    type="range"
                    min="0"
                    max="100"
                    value={rating}
                    onChange={(e) => setRating(parseInt(e.target.value))}
                    className="w-full h-1.5 bg-zinc-200 dark:bg-zinc-800 rounded-full appearance-none cursor-pointer accent-amber-600 hover:accent-amber-500 transition-all"
                />
                <div className="flex justify-between text-[9px] text-zinc-400 font-black uppercase tracking-widest px-1">
                    <span>Swill</span>
                    <span>Dram</span>
                    <span>Legendary</span>
                </div>
            </div>

            <div className="space-y-3">
                <label className="text-[11px] font-black text-zinc-400 uppercase tracking-widest">{t('tasting.overall')}</label>
                <div className="grid grid-cols-2 gap-2 p-1 bg-zinc-100 dark:bg-zinc-900/50 rounded-2xl border border-zinc-200/50 dark:border-zinc-800/50">
                    <button
                        type="button"
                        onClick={() => setIsSample(false)}
                        className={`py-2.5 px-4 rounded-xl text-xs font-black uppercase tracking-tight transition-all pb-3 ${!isSample
                            ? 'bg-white dark:bg-zinc-700 text-amber-600 shadow-sm ring-1 ring-black/5'
                            : 'text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-200'
                            }`}
                    >
                        Bottle
                    </button>
                    <button
                        type="button"
                        onClick={() => setIsSample(true)}
                        className={`py-2.5 px-4 rounded-xl text-xs font-black uppercase tracking-tight transition-all pb-3 ${isSample
                            ? 'bg-white dark:bg-zinc-700 text-amber-600 shadow-sm ring-1 ring-black/5'
                            : 'text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-200'
                            }`}
                    >
                        Sample
                    </button>
                </div>
            </div>

            <div className="space-y-4">
                <div className="bg-zinc-50 dark:bg-zinc-800/50 p-4 rounded-2xl border border-zinc-200 dark:border-zinc-700/50 space-y-4">
                    <TagSelector
                        category="nose"
                        selectedTagIds={noseTagIds}
                        onToggleTag={toggleNoseTag}
                        label={t('tasting.nose')}
                        suggestedTagNames={suggestedTags}
                        suggestedCustomTagNames={suggestedCustomTags}
                    />
                    <div className="space-y-2">
                        <label className="text-[10px] font-black text-zinc-400 uppercase tracking-widest block opacity-50">Zusätzliche Notizen</label>
                        <textarea
                            value={nose}
                            onChange={(e) => setNose(e.target.value)}
                            placeholder={t('tasting.notesPlaceholder')}
                            rows={2}
                            className="w-full p-3 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 rounded-xl text-sm focus:ring-2 focus:ring-amber-500 outline-none resize-none transition-all dark:text-zinc-200"
                        />
                    </div>
                </div>

                <div className="bg-zinc-50 dark:bg-zinc-800/50 p-4 rounded-2xl border border-zinc-200 dark:border-zinc-700/50 space-y-4">
                    <TagSelector
                        category="taste"
                        selectedTagIds={palateTagIds}
                        onToggleTag={togglePalateTag}
                        label={t('tasting.palate')}
                        suggestedTagNames={suggestedTags}
                        suggestedCustomTagNames={suggestedCustomTags}
                    />
                    <div className="space-y-2">
                        <label className="text-[10px] font-black text-zinc-400 uppercase tracking-widest block opacity-50">Zusätzliche Notizen</label>
                        <textarea
                            value={palate}
                            onChange={(e) => setPalate(e.target.value)}
                            placeholder={t('tasting.notesPlaceholder')}
                            rows={2}
                            className="w-full p-3 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 rounded-xl text-sm focus:ring-2 focus:ring-amber-500 outline-none resize-none transition-all dark:text-zinc-200"
                        />
                    </div>
                </div>

                <div className="bg-zinc-50 dark:bg-zinc-800/50 p-4 rounded-2xl border border-zinc-200 dark:border-zinc-700/50 space-y-6">
                    <TagSelector
                        category="finish"
                        selectedTagIds={finishTagIds}
                        onToggleTag={toggleFinishTag}
                        label={t('tasting.finish')}
                        suggestedTagNames={suggestedTags}
                        suggestedCustomTagNames={suggestedCustomTags}
                    />

                    <TagSelector
                        category="texture"
                        selectedTagIds={finishTagIds} // Using finish state for texture for now, or separate if needed
                        onToggleTag={toggleFinishTag}
                        label="Textur & Mundgefühl"
                        suggestedTagNames={suggestedTags}
                        suggestedCustomTagNames={suggestedCustomTags}
                    />

                    <div className="space-y-2">
                        <label className="text-[10px] font-black text-zinc-400 uppercase tracking-widest block opacity-50">Zusätzliche Notizen</label>
                        <textarea
                            value={finish}
                            onChange={(e) => setFinish(e.target.value)}
                            placeholder={t('tasting.notesPlaceholder')}
                            rows={2}
                            className="w-full p-3 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 rounded-xl text-sm focus:ring-2 focus:ring-amber-500 outline-none resize-none transition-all dark:text-zinc-200"
                        />
                    </div>
                </div>
            </div>

            {buddies.length > 0 && (
                <div className="space-y-3">
                    <label className="text-[11px] font-black text-zinc-400 uppercase tracking-widest flex items-center gap-2">
                        <Users size={14} className="text-amber-500" />
                        {t('tasting.participants')}
                    </label>
                    <div className="flex flex-wrap gap-2">
                        {buddies.map((buddy) => (
                            <button
                                key={buddy.id}
                                type="button"
                                onClick={() => toggleBuddy(buddy.id)}
                                className={`px-3 py-1.5 rounded-full text-[10px] font-black uppercase transition-all flex items-center gap-1.5 border shadow-sm ${selectedBuddyIds.includes(buddy.id)
                                    ? 'bg-amber-600 border-amber-600 text-white shadow-amber-600/20'
                                    : 'bg-white dark:bg-zinc-800 border-zinc-200 dark:border-zinc-700 text-zinc-500 dark:text-zinc-400 hover:border-amber-500/50'
                                    }`}
                            >
                                {selectedBuddyIds.includes(buddy.id) && <Check size={10} />}
                                {buddy.name}
                            </button>
                        ))}
                    </div>
                </div>
            )}

            {error && (
                <div className="p-3 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 text-xs rounded-lg border border-red-100 dark:border-red-900/50">
                    {error}
                </div>
            )}

            <button
                type="submit"
                disabled={loading}
                className="w-full py-4 bg-zinc-900 dark:bg-zinc-100 text-zinc-100 dark:text-zinc-900 font-black uppercase tracking-widest text-xs rounded-2xl flex items-center justify-center gap-3 hover:bg-amber-600 dark:hover:bg-amber-600 hover:text-white transition-all active:scale-[0.98] disabled:opacity-50 shadow-xl shadow-black/10 dark:shadow-amber-900/10"
            >
                {loading ? <Loader2 className="animate-spin" size={18} /> : (
                    <>
                        <Send size={16} />
                        {t('tasting.saveTasting')}
                    </>
                )}
            </button>
        </form>
    );
}
