'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, TrendingUp } 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';
import FlavorRadar from './FlavorRadar';


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 [isEditMode, setIsEditMode] = 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);

        // Haptic feedback for interaction
        if (window.navigator.vibrate) {
            window.navigator.vibrate(10);
        }

        try {
            await updateBottle(bottleId, {
                purchase_price: newPrice !== undefined ? (newPrice ? parseFloat(newPrice) : null) : (price ? parseFloat(price) : null),
                status: newStatus !== undefined ? newStatus : status
            } as any);

            // Success haptic
            if (window.navigator.vibrate) {
                window.navigator.vibrate([10, 50, 10]);
            }
        } 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 pb-24">
            {/* Header / Hero Section */}
            <div className="relative w-full overflow-hidden bg-[var(--surface)] shadow-2xl">
                {/* Back Button Overlay */}
                <div className="absolute top-6 left-6 z-20">
                    <Link
                        href={`/${sessionId ? `?session_id=${sessionId}` : ''}`}
                        className="flex items-center justify-center w-10 h-10 rounded-full bg-black/40 backdrop-blur-md text-white border border-white/10 active:scale-95 transition-all"
                    >
                        <ChevronLeft size={24} />
                    </Link>
                </div>

                {/* Hero Image - Slightly More Compact Aspect for better title flow */}
                <div className="relative aspect-[4/3] md:aspect-[16/8] w-full flex items-center justify-center p-6 md:p-10 overflow-hidden">
                    {/* Background Glow */}
                    <div className="absolute inset-0 bg-[radial-gradient(circle_at_center,_var(--tw-gradient-stops))] from-orange-600/10 via-transparent to-transparent opacity-30" />
                    <img
                        src={getStorageUrl(bottle.image_url)}
                        alt={bottle.name}
                        className="max-h-full max-w-full object-contain drop-shadow-[0_20px_60px_rgba(0,0,0,0.6)] z-10 transition-transform duration-700 hover:scale-105"
                    />
                </div>

                {/* Info Overlay - Mobile Gradient */}
                <div className="absolute inset-x-0 bottom-0 h-48 bg-gradient-to-t from-[var(--background)] to-transparent pointer-events-none" />
            </div>

            {/* Content Container */}
            <div className="px-4 md:px-12 -mt-12 relative z-10 space-y-8">
                {/* Title Section - HIG Large Title Pattern */}
                <div className="space-y-1 text-center md:text-left">
                    {isOffline && (
                        <div className="inline-flex bg-orange-600/10 border border-orange-600/20 px-3 py-1 rounded-full items-center gap-2 mb-2">
                            <WifiOff size={12} className="text-orange-600" />
                            <p className="text-[9px] font-black uppercase tracking-widest text-orange-500">Offline Mode</p>
                        </div>
                    )}
                    <h2 className="text-xs md:text-sm font-black text-orange-500 uppercase tracking-[0.25em] drop-shadow-sm">
                        {bottle.distillery || 'Unknown Distillery'}
                    </h2>
                    <h1 className="text-4xl md:text-6xl font-extrabold text-white tracking-tight leading-[1.05] drop-shadow-md">
                        {bottle.name}
                    </h1>
                </div>

                {/* Primary Bottle Profile Card */}
                <section className="bg-zinc-900/40 backdrop-blur-2xl border border-white/5 rounded-[32px] overflow-hidden shadow-2xl">
                    {/* Integrated Header/Tabs */}
                    <div className="flex border-b border-white/5">
                        <button
                            onClick={() => setIsEditMode(false)}
                            className={`flex-1 py-4 text-[10px] font-black uppercase tracking-[0.2em] transition-all ${!isEditMode ? 'text-orange-500 bg-white/5' : 'text-zinc-500 hover:text-zinc-300'}`}
                        >
                            Overview
                        </button>
                        <button
                            onClick={() => setIsEditMode(true)}
                            className={`flex-1 py-4 text-[10px] font-black uppercase tracking-[0.2em] transition-all ${isEditMode ? 'text-orange-500 bg-white/5' : 'text-zinc-500 hover:text-zinc-300'}`}
                        >
                            Edit Details
                        </button>
                    </div>

                    <AnimatePresence mode="wait">
                        {!isEditMode ? (
                            <motion.div
                                key="overview"
                                initial={{ opacity: 0, x: -20 }}
                                animate={{ opacity: 1, x: 0 }}
                                exit={{ opacity: 0, x: 20 }}
                                className="p-6 md:p-8 space-y-8"
                            >
                                {/* Flavor Profile Section */}
                                {tastings && tastings.some((t: any) => t.flavor_profile) && (
                                    <div className="bg-black/20 rounded-3xl border border-white/5 p-6 space-y-4">
                                        <div className="flex items-center gap-2 px-1">
                                            <TrendingUp size={14} className="text-orange-500" />
                                            <span className="text-[10px] font-black uppercase tracking-widest text-zinc-500">Average Flavor Profile</span>
                                        </div>
                                        <div className="flex flex-col md:flex-row items-center gap-6">
                                            <div className="w-full md:w-1/2">
                                                <FlavorRadar
                                                    profile={(() => {
                                                        const validProfiles = tastings.filter((t: any) => t.flavor_profile).map((t: any) => t.flavor_profile);
                                                        const count = validProfiles.length;
                                                        return {
                                                            smoky: Math.round(validProfiles.reduce((s, p) => s + p.smoky, 0) / count),
                                                            fruity: Math.round(validProfiles.reduce((s, p) => s + p.fruity, 0) / count),
                                                            spicy: Math.round(validProfiles.reduce((s, p) => s + p.spicy, 0) / count),
                                                            sweet: Math.round(validProfiles.reduce((s, p) => s + p.sweet, 0) / count),
                                                            floral: Math.round(validProfiles.reduce((s, p) => s + p.floral, 0) / count),
                                                        };
                                                    })()}
                                                    size={220}
                                                />
                                            </div>
                                            <div className="w-full md:w-1/2 space-y-2">
                                                <p className="text-xs text-zinc-400 leading-relaxed font-medium italic">
                                                    Basierend auf {tastings.filter((t: any) => t.flavor_profile).length} Verkostungen. Dieses Diagramm zeigt den durchschnittlichen Charakter dieser Flasche.
                                                </p>
                                                <div className="grid grid-cols-2 gap-2 pt-2">
                                                    {['smoky', 'fruity', 'spicy', 'sweet', 'floral'].map(attr => (
                                                        <div key={attr} className="flex items-center gap-2">
                                                            <div className="w-1.5 h-1.5 rounded-full bg-orange-600" />
                                                            <span className="text-[9px] font-black uppercase tracking-wider text-zinc-500">{attr}</span>
                                                        </div>
                                                    ))}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                )}

                                {/* Fact Grid - Integrated Metadata & Stats */}
                                <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
                                    <FactCard label="Category" value={bottle.category || 'Whisky'} icon={<Wine size={14} />} />
                                    <FactCard label="ABV" value={bottle.abv ? `${bottle.abv}%` : '%'} icon={<Droplets size={14} />} highlight={!bottle.abv} />
                                    <FactCard label="Age" value={bottle.age ? `${bottle.age}Y` : '-'} icon={<Award size={14} />} />
                                    <FactCard label="Price" value={bottle.purchase_price ? `${bottle.purchase_price}€` : '-'} icon={<CircleDollarSign size={14} />} />
                                    {(bottle as any).cask_type && (
                                        <div className="col-span-2">
                                            <FactCard label="Cask" value={(bottle as any).cask_type} icon={<Package size={14} />} />
                                        </div>
                                    )}
                                </div>

                                {/* Status & Last Dram Row */}
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    {/* Status Switcher */}
                                    <div className="space-y-3">
                                        <div className="flex items-center gap-2 px-1">
                                            <Package size={14} className="text-orange-500" />
                                            <span className="text-[10px] font-black uppercase tracking-widest text-zinc-500">Bottle Status</span>
                                        </div>
                                        <div className="grid grid-cols-3 bg-black/40 p-1 rounded-2xl border border-white/5">
                                            {['sealed', 'open', 'empty'].map((s) => (
                                                <button
                                                    key={s}
                                                    disabled={isOffline || isUpdating}
                                                    onClick={() => handleQuickUpdate(undefined, s)}
                                                    className={`py-3 rounded-xl text-[10px] font-black uppercase tracking-widest transition-all ${status === s
                                                        ? 'bg-orange-600 text-white shadow-lg'
                                                        : 'text-zinc-600 hover:text-zinc-400'
                                                        }`}
                                                >
                                                    {s}
                                                </button>
                                            ))}
                                        </div>
                                    </div>

                                    {/* Last Dram Info */}
                                    <div className="space-y-3">
                                        <div className="flex items-center gap-2 px-1">
                                            <Calendar size={14} className="text-orange-500" />
                                            <span className="text-[10px] font-black uppercase tracking-widest text-zinc-500">Last Enjoyed</span>
                                        </div>
                                        <div className="bg-black/40 rounded-2xl px-6 py-3.5 border border-white/5 flex items-center justify-between">
                                            <span className="text-sm font-black text-zinc-200 uppercase">
                                                {tastings?.length ? new Date(tastings[0].created_at).toLocaleDateString(locale === 'de' ? 'de-DE' : 'en-US', { day: '2-digit', month: '2-digit', year: 'numeric' }) : 'No dram yet'}
                                            </span>
                                            {tastings?.length > 0 && <CheckCircle2 size={16} className="text-orange-600" />}
                                        </div>
                                    </div>
                                </div>

                                {/* Whiskybase Link - Premium Style */}
                                {bottle.whiskybase_id && (
                                    <div className="pt-2">
                                        <a
                                            href={`https://www.whiskybase.com/whiskies/whisky/${bottle.whiskybase_id}`}
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            className="group flex items-center justify-between p-4 bg-orange-600/10 border border-orange-600/20 rounded-2xl hover:bg-orange-600/20 transition-all"
                                        >
                                            <div className="flex items-center gap-4">
                                                <div className="w-10 h-10 rounded-xl bg-orange-600 flex items-center justify-center text-white shadow-lg shadow-orange-950/40">
                                                    <ExternalLink size={20} />
                                                </div>
                                                <div>
                                                    <p className="text-[10px] font-black uppercase tracking-widest text-orange-400">View on Whiskybase</p>
                                                    <p className="text-sm font-black text-zinc-100">#{bottle.whiskybase_id}</p>
                                                </div>
                                            </div>
                                            <ChevronLeft size={20} className="rotate-180 text-orange-500 group-hover:translate-x-1 transition-transform" />
                                        </a>
                                    </div>
                                )}
                            </motion.div>
                        ) : (
                            <motion.div
                                key="edit"
                                initial={{ opacity: 0, x: 20 }}
                                animate={{ opacity: 1, x: 0 }}
                                exit={{ opacity: 0, x: -20 }}
                                className="p-6 md:p-8"
                            >
                                <EditBottleForm
                                    bottle={bottle as any}
                                    onComplete={() => setIsEditMode(false)}
                                />
                            </motion.div>
                        )}
                    </AnimatePresence>
                </section>

                {/* Secondary Actions */}
                {!isOffline && (
                    <div className="flex flex-col sm:flex-row gap-3 pt-4">
                        <Link
                            href={`/splits/create?bottle=${bottle.id}`}
                            className="flex-1 py-5 bg-zinc-900 border border-white/5 hover:border-orange-500/30 text-white rounded-2xl text-[11px] font-black uppercase tracking-[0.25em] flex items-center justify-center gap-3 transition-all active:scale-95 group shadow-xl"
                        >
                            <Share2 size={16} className="text-orange-500 group-hover:scale-110 transition-transform" />
                            Launch Split
                        </Link>
                        <DeleteBottleButton bottleId={bottle.id} />
                    </div>
                )}

                <hr className="border-white/5" />

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

// Premium Fact Card Sub-component
interface FactCardProps {
    label: string;
    value: string;
    icon: React.ReactNode;
    highlight?: boolean;
}

function FactCard({ label, value, icon, highlight }: FactCardProps) {
    return (
        <div className={`p-4 rounded-2xl border transition-all ${highlight ? 'bg-orange-600/10 border-orange-500/30 animate-pulse' : 'bg-black/20 border-white/5 hover:border-white/10'}`}>
            <div className="flex items-center gap-2 mb-1.5">
                <div className="text-orange-500">{icon}</div>
                <span className="text-[9px] font-black uppercase tracking-widest text-zinc-500">{label}</span>
            </div>
            <p className={`text-sm font-black uppercase tracking-tight ${highlight ? 'text-orange-400' : 'text-zinc-100'}`}>
                {value}
            </p>
        </div>
    );
}
