'use client';

import React from 'react';
import Link from 'next/link';
import { ChevronLeft, Calendar, Award, Droplets, MapPin, Tag, ExternalLink, Package, Info, Loader2, WifiOff, CircleDollarSign, Wine, CheckCircle2, Circle, ChevronDown, Plus, Share2 } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { updateBottle } from '@/services/update-bottle';
import { getStorageUrl } from '@/lib/supabase';
import TastingNoteForm from '@/components/TastingNoteForm';
import TastingList from '@/components/TastingList';
import DeleteBottleButton from '@/components/DeleteBottleButton';
import EditBottleForm from '@/components/EditBottleForm';
import { useBottleData } from '@/hooks/useBottleData';
import { useI18n } from '@/i18n/I18nContext';

interface BottleDetailsProps {
    bottleId: string;
    sessionId?: string;
    userId?: string;
}

export default function BottleDetails({ bottleId, sessionId, userId }: BottleDetailsProps) {
    const { t, locale } = useI18n();
    const { bottle, tastings, loading, error, isOffline } = useBottleData(bottleId);

    // Quick Collection States
    const [price, setPrice] = React.useState<string>('');
    const [status, setStatus] = React.useState<string>('sealed');
    const [isUpdating, setIsUpdating] = React.useState(false);
    const [isFormVisible, setIsFormVisible] = React.useState(false);

    React.useEffect(() => {
        if (bottle) {
            setPrice(bottle.purchase_price?.toString() || '');
            setStatus((bottle as any).status || 'sealed');
        }
    }, [bottle]);

    const handleQuickUpdate = async (newPrice?: string, newStatus?: string) => {
        if (isOffline) return;
        setIsUpdating(true);
        try {
            await updateBottle(bottleId, {
                purchase_price: newPrice !== undefined ? (newPrice ? parseFloat(newPrice) : null) : (price ? parseFloat(price) : null),
                status: newStatus !== undefined ? newStatus : status
            } as any);
        } catch (err) {
            console.error('Quick update failed:', err);
        } finally {
            setIsUpdating(false);
        }
    };

    if (loading) {
        return (
            <div className="min-h-[60vh] flex flex-col items-center justify-center gap-4">
                <Loader2 size={48} className="animate-spin text-orange-600" />
                <p className="text-zinc-500 font-bold animate-pulse uppercase tracking-widest text-xs">{t('common.loading')}</p>
            </div>
        );
    }

    if (!bottle && !loading) {
        return (
            <div className="min-h-[60vh] flex flex-col items-center justify-center gap-6 p-6 text-center">
                <div className="w-20 h-20 bg-zinc-900 rounded-full flex items-center justify-center text-zinc-500">
                    <WifiOff size={40} />
                </div>
                <div>
                    <h2 className="text-xl font-black text-zinc-50 mb-2">Flasche nicht verfügbar</h2>
                    <p className="text-zinc-500 text-sm max-w-xs mx-auto">
                        Inhalte konnten nicht geladen werden. Bitte stelle eine Internetverbindung her, um diese Flasche zum ersten Mal zu laden.
                    </p>
                </div>
                <Link href="/" className="px-6 py-3 bg-orange-600 text-white rounded-2xl text-sm font-black uppercase tracking-widest shadow-xl shadow-orange-950/20">
                    Zurück zum Vault
                </Link>
            </div>
        );
    }

    if (!bottle) return null; // Should not happen due to check above

    return (
        <div className="max-w-4xl mx-auto space-y-6 md:space-y-12">
            {/* Back Button */}
            <Link
                href={`/${sessionId ? `?session_id=${sessionId}` : ''}`}
                className="inline-flex items-center gap-2 text-zinc-500 hover:text-orange-600 transition-colors font-bold mb-4"
            >
                <ChevronLeft size={20} />
                Zurück zur Sammlung
            </Link>

            {isOffline && (
                <div className="bg-orange-600/10 border border-orange-600/20 p-3 rounded-2xl flex items-center gap-3 animate-in fade-in slide-in-from-top-2">
                    <WifiOff size={16} className="text-orange-600" />
                    <p className="text-[10px] font-bold uppercase tracking-widest text-orange-500">Offline-Modus: Daten aus dem Cache</p>
                </div>
            )}

            {/* Hero Section */}
            <section className="grid grid-cols-1 md:grid-cols-2 gap-8 items-start">
                <div className="aspect-[4/5] rounded-3xl overflow-hidden shadow-2xl border border-zinc-800 bg-zinc-900">
                    <img
                        src={getStorageUrl(bottle.image_url)}
                        alt={bottle.name}
                        className="w-full h-full object-cover"
                    />
                </div>

                <div className="space-y-6">
                    <div>
                        <h1 className="text-2xl md:text-4xl font-bold text-zinc-50 tracking-tighter leading-tight uppercase">
                            {bottle.name}
                        </h1>
                        <p className="text-sm md:text-xl text-orange-600 font-bold mt-1 uppercase tracking-widest">{bottle.distillery}</p>

                        {bottle.whiskybase_id && (
                            <div className="mt-4">
                                <a
                                    href={`https://www.whiskybase.com/whiskies/whisky/${bottle.whiskybase_id}`}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="inline-flex items-center gap-2 px-4 py-2 bg-zinc-900 text-zinc-400 border border-zinc-800 rounded-xl text-xs font-bold hover:text-orange-600 transition-colors"
                                >
                                    <ExternalLink size={14} />
                                    Whiskybase ID: {bottle.whiskybase_id}
                                </a>
                            </div>
                        )}
                    </div>

                    <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                        <div className="p-4 bg-zinc-900 rounded-2xl border border-zinc-800 shadow-sm flex flex-col justify-between">
                            <div>
                                <div className="flex items-center gap-2 text-zinc-500 text-[10px] font-bold uppercase mb-1">
                                    <Tag size={12} /> Kategorie
                                </div>
                                <div className="font-bold text-sm text-zinc-200">{bottle.category || '-'}</div>
                            </div>
                        </div>
                        <div className="p-4 bg-zinc-900 rounded-2xl border border-zinc-800 shadow-sm">
                            <div className="flex items-center gap-2 text-zinc-500 text-[10px] font-bold uppercase mb-1">
                                <Droplets size={12} /> Alkoholgehalt
                            </div>
                            <div className="font-bold text-sm text-zinc-200">{bottle.abv}% Vol.</div>
                        </div>
                        <div className="p-4 bg-zinc-900 rounded-2xl border border-zinc-800 shadow-sm">
                            <div className="flex items-center gap-2 text-zinc-500 text-[10px] font-bold uppercase mb-1">
                                <Award size={12} /> Alter
                            </div>
                            <div className="font-bold text-sm text-zinc-200">{bottle.age ? `${bottle.age} J.` : '-'}</div>
                        </div>

                        {bottle.distilled_at && (
                            <div className="p-4 bg-zinc-900 rounded-2xl border border-zinc-800 shadow-sm">
                                <div className="flex items-center gap-2 text-zinc-500 text-[10px] font-bold uppercase mb-1">
                                    <Calendar size={12} /> Destilliert
                                </div>
                                <div className="font-bold text-sm text-zinc-200">{bottle.distilled_at}</div>
                            </div>
                        )}

                        {bottle.bottled_at && (
                            <div className="p-4 bg-zinc-900 rounded-2xl border border-zinc-800 shadow-sm">
                                <div className="flex items-center gap-2 text-zinc-500 text-[10px] font-bold uppercase mb-1">
                                    <Package size={12} /> Abgefüllt
                                </div>
                                <div className="font-bold text-sm text-zinc-200">{bottle.bottled_at}</div>
                            </div>
                        )}

                        {/* Quick Collection Card */}
                        <div className="md:col-span-2 p-5 bg-orange-600/5 rounded-3xl border border-orange-600/20 shadow-xl space-y-4">
                            <div className="flex items-center justify-between">
                                <h3 className="text-[10px] font-black uppercase tracking-[0.2em] text-orange-600 flex items-center gap-2">
                                    <Package size={14} /> Sammlungs-Status
                                </h3>
                                {isUpdating && <Loader2 size={12} className="animate-spin text-orange-600" />}
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                {/* Price */}
                                <div className="space-y-1.5">
                                    <label className="text-[9px] font-bold uppercase text-zinc-500 ml-1">Einkaufspreis</label>
                                    <div className="relative">
                                        <input
                                            type="number"
                                            step="0.01"
                                            value={price}
                                            onChange={(e) => setPrice(e.target.value)}
                                            onBlur={() => handleQuickUpdate(price)}
                                            placeholder="0.00"
                                            className="w-full bg-zinc-950 border border-zinc-800 rounded-xl pl-3 pr-8 py-2 text-sm font-bold text-orange-500 focus:outline-none focus:border-orange-600 transition-all"
                                        />
                                        <div className="absolute right-3 top-1/2 -translate-y-1/2 text-[10px] font-bold text-zinc-700">€</div>
                                    </div>
                                </div>

                                {/* Status */}
                                <div className="space-y-1.5">
                                    <label className="text-[9px] font-bold uppercase text-zinc-500 ml-1">Flaschenstatus</label>
                                    <select
                                        value={status}
                                        onChange={(e) => {
                                            setStatus(e.target.value);
                                            handleQuickUpdate(undefined, e.target.value);
                                        }}
                                        className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-3 py-2 text-sm font-bold text-zinc-200 focus:outline-none focus:border-orange-600 appearance-none transition-all"
                                    >
                                        <option value="sealed">Versiegelt</option>
                                        <option value="open">Offen</option>
                                        <option value="sampled">Sample</option>
                                        <option value="empty">Leer</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        {bottle.batch_info && (
                            <div className="p-4 bg-zinc-800/30 rounded-2xl border border-dashed border-zinc-700/50 md:col-span-1">
                                <div className="flex items-center gap-2 text-zinc-500 text-[10px] font-bold uppercase mb-1">
                                    <Info size={12} /> Batch / Code
                                </div>
                                <div className="font-mono text-xs text-zinc-300 truncate" title={bottle.batch_info}>{bottle.batch_info}</div>
                            </div>
                        )}

                        <div className="p-4 bg-zinc-900 rounded-2xl border border-zinc-800 shadow-sm">
                            <div className="flex items-center gap-2 text-zinc-500 text-[10px] font-bold uppercase mb-1">
                                <Calendar size={12} /> Letzter Dram
                            </div>
                            <div className="font-bold text-sm text-zinc-200">
                                {tastings && tastings.length > 0
                                    ? new Date(tastings[0].created_at).toLocaleDateString('de-DE')
                                    : 'Noch nie'}
                            </div>
                        </div>
                    </div>

                    <div className="pt-2 flex flex-wrap gap-4">
                        {isOffline ? (
                            <div className="w-full p-4 bg-zinc-900 border border-dashed border-zinc-800 rounded-2xl flex items-center justify-center gap-2">
                                <Info size={14} className="text-zinc-500" />
                                <span className="text-[10px] font-bold uppercase text-zinc-500 tracking-widest">Bearbeiten & Löschen nur online möglich</span>
                            </div>
                        ) : (
                            <>
                                <EditBottleForm bottle={bottle as any} />
                                <Link
                                    href={`/splits/create?bottle=${bottle.id}`}
                                    className="px-5 py-3 bg-zinc-800 hover:bg-zinc-700 text-white rounded-2xl text-xs font-black uppercase tracking-widest flex items-center gap-2 transition-all border border-zinc-700 hover:border-orange-600/50"
                                >
                                    <Share2 size={16} className="text-orange-500" />
                                    Split starten
                                </Link>
                                <DeleteBottleButton bottleId={bottle.id} />
                            </>
                        )}
                    </div>
                </div>
            </section>

            <hr className="border-zinc-800" />

            {/* Tasting Notes Section */}
            <section className="space-y-8">
                <div className="flex flex-col md:flex-row justify-between items-start md:items-end gap-4">
                    <div>
                        <h2 className="text-3xl font-bold text-zinc-50 tracking-tight uppercase">Tasting Notes</h2>
                        <p className="text-zinc-500 mt-1">Hier findest du deine bisherigen Eindrücke.</p>
                    </div>
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 md:gap-8 items-start">
                    {/* Form */}
                    <div className="lg:col-span-1 space-y-4 md:sticky md:top-24">
                        <button
                            onClick={() => setIsFormVisible(!isFormVisible)}
                            className={`w-full p-6 rounded-3xl border flex items-center justify-between transition-all group ${isFormVisible ? 'bg-orange-600 border-orange-600 text-white shadow-xl shadow-orange-950/40' : 'bg-zinc-900/50 border-zinc-800 text-zinc-400 hover:border-orange-500/30'}`}
                        >
                            <div className="flex items-center gap-3">
                                {isFormVisible ? <Plus size={20} className="rotate-45 transition-transform" /> : <Plus size={20} className="text-orange-600 transition-transform" />}
                                <span className={`text-sm font-black uppercase tracking-widest ${isFormVisible ? 'text-white' : 'text-zinc-100'}`}>Neue Tasting Note</span>
                            </div>
                            <ChevronDown size={20} className={`transition-transform duration-300 ${isFormVisible ? 'rotate-180' : 'opacity-0'}`} />
                        </button>

                        <AnimatePresence>
                            {isFormVisible && (
                                <motion.div
                                    initial={{ opacity: 0, y: -20, height: 0 }}
                                    animate={{ opacity: 1, y: 0, height: 'auto' }}
                                    exit={{ opacity: 0, y: -20, height: 0 }}
                                    className="overflow-hidden"
                                >
                                    <div className="border border-zinc-800 rounded-3xl p-6 bg-zinc-900/50">
                                        <h3 className="text-lg font-bold mb-6 flex items-center gap-2 text-orange-600 uppercase tracking-widest">
                                            <Droplets size={20} /> Dram bewerten
                                        </h3>
                                        <TastingNoteForm
                                            bottleId={bottle.id}
                                            sessionId={sessionId}
                                            onSuccess={() => setIsFormVisible(false)}
                                        />
                                    </div>
                                </motion.div>
                            )}
                        </AnimatePresence>
                    </div>

                    {/* List */}
                    <div className="lg:col-span-2">
                        <TastingList initialTastings={tastings as any || []} currentUserId={userId} />
                    </div>
                </div>
            </section>
        </div>
    );
}
