'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, ChevronDown } from 'lucide-react';
import { createClient } from '@/lib/supabase/client';
import { useI18n } from '@/i18n/I18nContext';
import { useSession } from '@/context/SessionContext';
import TagSelector from './TagSelector';
import { db } from '@/lib/db';
import { useAuth } from '@/context/AuthContext';
import { useLiveQuery } from 'dexie-react-hooks';
import { AlertTriangle } from 'lucide-react';
import TastingFormBody from './TastingFormBody';

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 { user, isLoading: isAuthLoading } = useAuth();
    const [lastDramInSession, setLastDramInSession] = useState<{ name: string; isSmoky: boolean; timestamp: number } | null>(null);
    const [showPaletteWarning, setShowPaletteWarning] = useState(false);

    const [bottleOwnerId, setBottleOwnerId] = useState<string | null>(null);
    const [currentUserId, setCurrentUserId] = useState<string | null>(null);

    // Section collapse states
    const [isNoseExpanded, setIsNoseExpanded] = useState(false);
    const [isPalateExpanded, setIsPalateExpanded] = useState(false);
    const [isFinishExpanded, setIsFinishExpanded] = useState(false);

    const effectiveSessionId = sessionId || activeSession?.id;

    useEffect(() => {
        if (!isAuthLoading && user) {
            setCurrentUserId(user.id);
        }
    }, [user, isAuthLoading]);

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

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

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

            // 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, user, isAuthLoading]);

    // 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);
        }
    };

    const isSharedBottle = bottleOwnerId && currentUserId && bottleOwnerId !== currentUserId;

    return (
        <form onSubmit={handleSubmit} className="space-y-6">
            {isSharedBottle && !activeSession && (
                <div className="p-4 bg-orange-500/10 border border-orange-500/20 rounded-2xl flex items-start gap-3">
                    <AlertTriangle size={20} className="text-orange-500 shrink-0 mt-0.5" />
                    <div>
                        <p className="text-[10px] font-black uppercase tracking-wider text-orange-600">Shared Bottle Ownership Check</p>
                        <p className="text-xs font-bold text-orange-200">Diese Flasche gehört einem Buddy.</p>
                        <p className="text-[10px] text-orange-400/80 leading-relaxed font-medium mt-1">
                            Hinweis: Falls kein Session-Sharing aktiv ist, schlägt das Speichern fehl. Starte eine Session um gemeinsam zu bewerten!
                        </p>
                    </div>
                </div>
            )}
            {activeSession && (
                <div className="p-3 bg-orange-950/20 border border-orange-900/30 rounded-2xl flex items-center gap-3 animate-in fade-in slide-in-from-top-2">
                    <div className="bg-orange-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-orange-500">Recording for Session</p>
                        <p className="text-xs font-bold text-orange-200 truncate">{activeSession.name}</p>
                    </div>
                </div>
            )}

            {showPaletteWarning && (
                <div className="p-4 bg-orange-500/10 border border-orange-500/20 rounded-2xl flex items-start gap-3 animate-in fade-in slide-in-from-top-2">
                    <AlertTriangle size={20} className="text-orange-500 shrink-0 mt-0.5" />
                    <div className="space-y-1">
                        <p className="text-[10px] font-black uppercase tracking-wider text-orange-600">Palette-Checker Warnung</p>
                        <p className="text-xs font-bold text-orange-200">
                            Dein letzter Dram war "{lastDramInSession?.name}".
                        </p>
                        <p className="text-[10px] text-orange-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-orange-600 underline"
                        >
                            Ignorieren
                        </button>
                    </div>
                </div>
            )}

            <TastingFormBody
                rating={rating}
                setRating={setRating}
                isSample={isSample}
                setIsSample={setIsSample}
                nose={nose}
                setNose={setNose}
                noseTagIds={noseTagIds}
                setNoseTagIds={setNoseTagIds}
                palate={palate}
                setPalate={setPalate}
                palateTagIds={palateTagIds}
                setPalateTagIds={setPalateTagIds}
                finish={finish}
                setFinish={setFinish}
                finishTagIds={finishTagIds}
                setFinishTagIds={setFinishTagIds}
                selectedBuddyIds={selectedBuddyIds}
                setSelectedBuddyIds={setSelectedBuddyIds}
                availableBuddies={buddies}
                suggestedTags={suggestedTags}
                suggestedCustomTags={suggestedCustomTags}
                t={t}
            />

            {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>
            )}

            {/* Sticky Save Button Container */}
            <div className="sticky bottom-0 -mx-6 px-6 py-4 bg-gradient-to-t from-zinc-950 via-zinc-950/90 to-transparent z-10">
                <button
                    type="submit"
                    disabled={loading}
                    className="w-full py-4 bg-zinc-100 text-zinc-900 font-black uppercase tracking-widest text-xs rounded-2xl flex items-center justify-center gap-3 hover:bg-orange-600 hover:text-white transition-all active:scale-[0.98] disabled:opacity-50 shadow-2xl shadow-black/50 border border-white/5"
                >
                    {loading ? <Loader2 className="animate-spin" size={18} /> : (
                        <>
                            <Send size={16} />
                            {t('tasting.saveTasting')}
                        </>
                    )}
                </button>
            </div>
        </form>
    );
}
