'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 { createClientComponentClient } from '@supabase/auth-helpers-nextjs';
import { useI18n } from '@/i18n/I18nContext';
import { useSession } from '@/context/SessionContext';
import TagSelector from './TagSelector';

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

interface TastingNoteFormProps {
    bottleId: string;
    sessionId?: string;
}

export default function TastingNoteForm({ bottleId, sessionId }: TastingNoteFormProps) {
    const { t } = useI18n();
    const supabase = createClientComponentClient();
    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, setBuddies] = useState<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 effectiveSessionId = sessionId || activeSession?.id;

    useEffect(() => {
        const fetchData = async () => {
            // Fetch All Buddies
            const { data: buddiesData } = await supabase.from('buddies').select('id, name').order('name');
            setBuddies(buddiesData || []);

            // 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
            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));
                }
            } else {
                setSelectedBuddyIds([]);
            }
        };
        fetchData();
    }, [effectiveSessionId, bottleId]);

    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 handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setLoading(true);
        setError(null);

        try {
            const result = await saveTasting({
                bottle_id: bottleId,
                session_id: effectiveSessionId,
                rating,
                nose_notes: nose,
                palate_notes: palate,
                finish_notes: finish,
                is_sample: isSample,
                buddy_ids: selectedBuddyIds,
                tag_ids: [...noseTagIds, ...palateTagIds, ...finishTagIds],
            });

            if (result.success) {
                setNose('');
                setPalate('');
                setFinish('');
                setSelectedBuddyIds([]);
                setNoseTagIds([]);
                setPalateTagIds([]);
                setFinishTagIds([]);
                // We don't need to manually refresh because of revalidatePath in the server action
            } 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>
            )}

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