'use client';

import React, { useState, useMemo } from 'react';
import Link from 'next/link';
import { Search, Filter, X, Calendar, Clock, Package, Lock, Unlock, Ghost, FlaskConical, AlertCircle, Trash2, AlertTriangle, PlusCircle } from 'lucide-react';
import { getStorageUrl } from '@/lib/supabase';
import { useSearchParams } from 'next/navigation';

interface Bottle {
    id: string;
    name: string;
    distillery: string;
    category: string;
    abv: number;
    age: number;
    image_url: string;
    status: 'sealed' | 'open' | 'sampled' | 'empty';
    created_at: string;
    last_tasted?: string | null;
    is_whisky?: boolean;
    confidence?: number;
}

interface BottleCardProps {
    bottle: Bottle;
    sessionId?: string | null;
}

function BottleCard({ bottle, sessionId }: BottleCardProps) {
    const statusConfig = {
        open: { icon: Unlock, color: 'bg-amber-500/80 border-amber-400/50', label: 'Offen' },
        sampled: { icon: FlaskConical, color: 'bg-purple-500/80 border-purple-400/50', label: 'Sample' },
        empty: { icon: Ghost, color: 'bg-zinc-500/80 border-zinc-400/50', label: 'Leer' },
        sealed: { icon: Lock, color: 'bg-blue-600/80 border-blue-400/50', label: 'Versiegelt' },
    };

    const StatusIcon = statusConfig[bottle.status as keyof typeof statusConfig]?.icon || Lock;
    const statusStyle = statusConfig[bottle.status as keyof typeof statusConfig] || statusConfig.sealed;

    return (
        <Link
            href={`/bottles/${bottle.id}${sessionId ? `?session_id=${sessionId}` : ''}`}
            className="block h-full group"
        >
            <div className="h-full bg-white dark:bg-zinc-900 rounded-[2rem] overflow-hidden border border-zinc-200 dark:border-zinc-800 shadow-sm transition-all duration-300 hover:shadow-2xl hover:shadow-amber-900/10 hover:-translate-y-1 group-hover:border-amber-500/30">
                <div className="aspect-[4/3] overflow-hidden bg-zinc-100 dark:bg-zinc-800 relative">
                    <img
                        src={getStorageUrl(bottle.image_url)}
                        alt={bottle.name}
                        className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                    />
                    <div className="absolute inset-0 bg-gradient-to-t from-black/40 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity" />

                    {sessionId && (
                        <div className="absolute top-3 left-3 bg-amber-600 text-white text-[9px] font-black px-2 py-1.5 rounded-xl flex items-center gap-1.5 border border-amber-400 shadow-xl animate-in slide-in-from-left-4 duration-500">
                            <PlusCircle size={12} strokeWidth={3} />
                            ZU SESSION HINZUFÜGEN
                        </div>
                    )}

                    {bottle.last_tasted && (
                        <div className="absolute top-3 right-3 bg-zinc-900/80 backdrop-blur-md text-white text-[9px] font-black px-2 py-1 rounded-lg flex items-center gap-1 border border-white/10 ring-1 ring-black/5">
                            <Clock size={10} />
                            {new Date(bottle.last_tasted).toLocaleDateString('de-DE')}
                        </div>
                    )}

                    <div className={`absolute bottom-3 left-3 px-3 py-1.5 rounded-xl text-[10px] font-black uppercase flex items-center gap-2 backdrop-blur-md border shadow-lg ${statusStyle.color}`}>
                        <StatusIcon size={12} />
                        {statusStyle.label}
                    </div>
                </div>

                <div className="p-3 md:p-5 space-y-3 md:space-y-4">
                    <div>
                        <div className="flex justify-between items-start mb-1">
                            <p className="text-[9px] md:text-[10px] font-black text-amber-600 uppercase tracking-[0.2em] leading-none">{bottle.distillery}</p>
                            {(bottle.is_whisky === false || (bottle.confidence && bottle.confidence < 70)) && (
                                <div className="flex items-center gap-1 text-[8px] font-black bg-red-500 text-white px-1.5 py-0.5 rounded-full animate-pulse">
                                    <AlertCircle size={8} />
                                    REVIEW
                                </div>
                            )}
                        </div>
                        <h3 className={`font-black text-lg md:text-xl leading-tight group-hover:text-amber-600 transition-colors line-clamp-2 min-h-[3rem] md:min-h-[3.5rem] flex items-center ${bottle.is_whisky === false ? 'text-red-600 dark:text-red-400' : 'text-zinc-900 dark:text-zinc-100'
                            }`}>
                            {bottle.name || 'Unbekannte Flasche'}
                        </h3>
                    </div>

                    <div className="flex flex-wrap gap-1.5 md:gap-2">
                        <span className="px-2 py-0.5 md:px-2.5 md:py-1 bg-zinc-100 dark:bg-zinc-800 text-zinc-600 dark:text-zinc-400 text-[9px] md:text-[10px] font-black uppercase tracking-widest rounded-lg border border-zinc-200/50 dark:border-zinc-700/50">
                            {bottle.category}
                        </span>
                        <span className="px-2 py-0.5 md:px-2.5 md:py-1 bg-amber-50 dark:bg-amber-900/20 text-amber-700 dark:text-amber-400 text-[9px] md:text-[10px] font-black uppercase tracking-widest rounded-lg border border-amber-200/50 dark:border-amber-800/20">
                            {bottle.abv}% VOL
                        </span>
                    </div>

                    <div className="pt-1 md:pt-2 flex items-center gap-2 text-[9px] md:text-[10px] font-bold text-zinc-400 uppercase tracking-wider border-t border-zinc-100 dark:border-zinc-800">
                        <Calendar size={10} className="text-zinc-300" />
                        <span className="opacity-70 text-[8px] md:text-[9px]">Hinzugefügt am</span>
                        <span className="text-zinc-500 dark:text-zinc-300">{new Date(bottle.created_at).toLocaleDateString('de-DE')}</span>
                    </div>
                </div>
            </div>
        </Link>
    );
}

interface BottleGridProps {
    bottles: any[];
}

export default function BottleGrid({ bottles }: BottleGridProps) {
    const searchParams = useSearchParams();
    const sessionId = searchParams.get('session_id');

    const [searchQuery, setSearchQuery] = useState('');
    const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
    const [selectedDistillery, setSelectedDistillery] = useState<string | null>(null);
    const [selectedStatus, setSelectedStatus] = useState<string | null>(null);
    const [sortBy, setSortBy] = useState<'name' | 'last_tasted' | 'created_at'>('created_at');

    const categories = useMemo(() => {
        const cats = new Set(bottles.map(b => b.category).filter(Boolean));
        return Array.from(cats).sort() as string[];
    }, [bottles]);

    const distilleries = useMemo(() => {
        const dists = new Set(bottles.map(b => b.distillery).filter(Boolean));
        return Array.from(dists).sort() as string[];
    }, [bottles]);

    const filteredBottles = useMemo(() => {
        let result = bottles.filter((bottle) => {
            const matchesSearch =
                bottle.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
                bottle.distillery?.toLowerCase().includes(searchQuery.toLowerCase());

            const matchesCategory = !selectedCategory || bottle.category === selectedCategory;
            const matchesDistillery = !selectedDistillery || bottle.distillery === selectedDistillery;
            const matchesStatus = !selectedStatus || bottle.status === selectedStatus;

            return matchesSearch && matchesCategory && matchesDistillery && matchesStatus;
        });

        // Sorting logic
        return result.sort((a, b) => {
            if (sortBy === 'name') {
                return (a.name || '').localeCompare(b.name || '');
            } else if (sortBy === 'last_tasted') {
                const dateA = a.last_tasted ? new Date(a.last_tasted).getTime() : 0;
                const dateB = b.last_tasted ? new Date(b.last_tasted).getTime() : 0;
                return dateB - dateA;
            } else { // sortBy === 'created_at'
                return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
            }
        });
    }, [bottles, searchQuery, selectedCategory, selectedDistillery, selectedStatus, sortBy]);

    if (!bottles || bottles.length === 0) {
        return (
            <div className="text-center py-12 p-8 bg-zinc-50 dark:bg-zinc-900/50 rounded-3xl border-2 border-dashed border-zinc-200 dark:border-zinc-800">
                <p className="text-zinc-500">Noch keine Flaschen im Vault. Zeit für den ersten Scan! 🥃</p>
            </div>
        );
    }

    return (
        <div className="w-full space-y-8">
            {/* Search and Filters */}
            <div className="w-full max-w-6xl mx-auto px-4 space-y-6">
                <div className="flex flex-col md:flex-row gap-4">
                    <div className="relative flex-1">
                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-400" size={18} />
                        <input
                            type="text"
                            placeholder="Suchen nach Name oder Distille..."
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                            className="w-full pl-10 pr-4 py-3 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 rounded-xl focus:ring-2 focus:ring-amber-500 outline-none transition-all"
                        />
                        {searchQuery && (
                            <button
                                onClick={() => setSearchQuery('')}
                                className="absolute right-3 top-1/2 -translate-y-1/2 text-zinc-400 hover:text-zinc-600"
                            >
                                <X size={16} />
                            </button>
                        )}
                    </div>

                    <select
                        value={sortBy}
                        onChange={(e) => setSortBy(e.target.value as any)}
                        className="px-4 py-3 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 rounded-xl text-sm font-medium focus:ring-2 focus:ring-amber-500 outline-none cursor-pointer"
                    >
                        <option value="created_at">Neueste zuerst</option>
                        <option value="last_tasted">Zuletzt verkostet</option>
                        <option value="name">Alphabetisch</option>
                    </select>
                </div>

                <div className="space-y-6">
                    {/* Category Filter */}
                    <div className="flex flex-col gap-2">
                        <span className="text-[10px] font-black uppercase tracking-widest text-zinc-400 px-1">Kategorie</span>
                        <div className="flex gap-2 overflow-x-auto -mx-4 px-4 pb-2 scrollbar-hide touch-pan-x">
                            <button
                                onClick={() => setSelectedCategory(null)}
                                className={`px-3 py-1.5 md:px-4 md:py-2 rounded-xl text-[10px] md:text-xs font-bold whitespace-nowrap transition-all border ${selectedCategory === null
                                    ? 'bg-amber-600 border-amber-600 text-white shadow-lg shadow-amber-600/20'
                                    : 'bg-white dark:bg-zinc-900 border-zinc-200 dark:border-zinc-800 text-zinc-600 dark:text-zinc-400'
                                    }`}
                            >
                                ALLE
                            </button>
                            {categories.map((cat) => (
                                <button
                                    key={cat}
                                    onClick={() => setSelectedCategory(cat)}
                                    className={`px-3 py-1.5 md:px-4 md:py-2 rounded-xl text-[10px] md:text-xs font-bold whitespace-nowrap transition-all border ${selectedCategory === cat
                                        ? 'bg-amber-600 border-amber-600 text-white shadow-lg shadow-amber-600/20'
                                        : 'bg-white dark:bg-zinc-900 border-zinc-200 dark:border-zinc-800 text-zinc-600 dark:text-zinc-400'
                                        }`}
                                >
                                    {cat.toUpperCase()}
                                </button>
                            ))}
                        </div>
                    </div>

                    {/* Distillery Filter */}
                    <div className="flex flex-col gap-2">
                        <span className="text-[10px] font-black uppercase tracking-widest text-zinc-400 px-1">Distillery</span>
                        <div className="flex gap-2 overflow-x-auto -mx-4 px-4 pb-2 scrollbar-hide touch-pan-x">
                            <button
                                onClick={() => setSelectedDistillery(null)}
                                className={`px-3 py-1.5 md:px-4 md:py-2 rounded-xl text-[10px] md:text-xs font-bold whitespace-nowrap transition-all border ${selectedDistillery === null
                                    ? 'bg-zinc-900 dark:bg-white text-white dark:text-zinc-900 border-zinc-900 dark:border-white'
                                    : 'bg-white dark:bg-zinc-900 border-zinc-200 dark:border-zinc-800 text-zinc-600 dark:text-zinc-400'
                                    }`}
                            >
                                ALLE
                            </button>
                            {distilleries.map((dist) => (
                                <button
                                    key={dist}
                                    onClick={() => setSelectedDistillery(dist)}
                                    className={`px-3 py-1.5 md:px-4 md:py-2 rounded-xl text-[10px] md:text-xs font-bold whitespace-nowrap transition-all border ${selectedDistillery === dist
                                        ? 'bg-zinc-900 dark:bg-white text-white dark:text-zinc-900 border-zinc-900 dark:border-white'
                                        : 'bg-white dark:bg-zinc-900 border-zinc-200 dark:border-zinc-800 text-zinc-600 dark:text-zinc-400'
                                        }`}
                                >
                                    {dist.toUpperCase()}
                                </button>
                            ))}
                        </div>
                    </div>

                    {/* Status Filter */}
                    <div className="flex flex-col gap-2">
                        <span className="text-[10px] font-black uppercase tracking-widest text-zinc-400 px-1">Status</span>
                        <div className="flex gap-2 overflow-x-auto -mx-4 px-4 pb-2 scrollbar-hide touch-pan-x">
                            {['sealed', 'open', 'sampled', 'empty'].map((status) => (
                                <button
                                    key={status}
                                    onClick={() => setSelectedStatus(selectedStatus === status ? null : status)}
                                    className={`px-3 py-1.5 md:px-4 md:py-2 rounded-xl text-[10px] md:text-xs font-bold whitespace-nowrap transition-all border ${selectedStatus === status
                                        ? status === 'open' ? 'bg-amber-500 border-amber-500 text-white' : status === 'sampled' ? 'bg-purple-500 border-purple-500 text-white' : status === 'empty' ? 'bg-zinc-500 border-zinc-500 text-white' : 'bg-blue-600 border-blue-600 text-white'
                                        : 'bg-white dark:bg-zinc-900 border-zinc-200 dark:border-zinc-800 text-zinc-600 dark:text-zinc-400'
                                        }`}
                                >
                                    {status.toUpperCase()}
                                </button>
                            ))}
                        </div>
                    </div>
                </div>
            </div>

            {/* Grid */}
            {filteredBottles.length > 0 ? (
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 w-full max-w-6xl mx-auto px-4">
                    {filteredBottles.map((bottle) => (
                        <BottleCard key={bottle.id} bottle={bottle} sessionId={sessionId} />
                    ))}
                </div>
            ) : (
                <div className="text-center py-12">
                    <p className="text-zinc-500 italic">Keine Flaschen gefunden, die deinen Filtern entsprechen. 🔎</p>
                </div>
            )}
        </div>
    );
}
