'use client';

import React, { useState, useMemo } from 'react';
import Link from 'next/link';
import { Search, Filter, X, Calendar, Clock, Package, Lock, Unlock, Ghost, FlaskConical } from 'lucide-react';

interface BottleCardProps {
    bottle: any;
}

function BottleCard({ bottle }: BottleCardProps) {
    return (
        <Link href={`/bottles/${bottle.id}`} className="block">
            <div className="bg-white dark:bg-zinc-900 rounded-2xl overflow-hidden border border-zinc-200 dark:border-zinc-800 shadow-md transition-all hover:scale-[1.02] hover:shadow-xl group relative">
                <div className="aspect-[3/2] overflow-hidden bg-zinc-100 dark:bg-zinc-800 relative">
                    <img
                        src={bottle.image_url}
                        alt={bottle.name}
                        className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
                    />
                    <div className="absolute inset-0 bg-black/0 group-hover:bg-black/10 transition-colors" />

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

                    <div className={`absolute bottom-3 left-3 px-2 py-1 rounded-md text-[10px] font-black uppercase flex items-center gap-1.5 backdrop-blur-md border ${bottle.status === 'open'
                        ? 'bg-amber-500/80 text-white border-amber-400/50'
                        : bottle.status === 'sampled'
                            ? 'bg-purple-500/80 text-white border-purple-400/50'
                            : bottle.status === 'empty'
                                ? 'bg-zinc-500/80 text-white border-zinc-400/50'
                                : 'bg-blue-600/80 text-white border-blue-400/50'
                        }`}>
                        {bottle.status === 'open' ? <Unlock size={10} /> : bottle.status === 'sampled' ? <FlaskConical size={10} /> : bottle.status === 'empty' ? <Ghost size={10} /> : <Lock size={10} />}
                        {bottle.status}
                    </div>
                </div>
                <div className="p-4">
                    <h3 className="font-bold text-lg text-zinc-800 dark:text-zinc-100 truncate">{bottle.name}</h3>
                    <p className="text-zinc-500 text-sm truncate">{bottle.distillery}</p>

                    <div className="mt-2 flex items-center gap-1.5 text-[10px] font-bold text-zinc-400 uppercase tracking-tight">
                        <Clock size={12} />
                        Hinzugefügt am {new Date(bottle.created_at).toLocaleDateString('de-DE')}
                    </div>

                    <div className="mt-3 flex items-center justify-between">
                        <span className="px-2 py-1 bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 text-xs font-semibold rounded-md">
                            {bottle.category}
                        </span>
                        <span className="text-xs text-zinc-400">
                            {bottle.abv}% Vol.
                        </span>
                    </div>
                </div>
            </div>
        </Link>
    );
}

interface BottleGridProps {
    bottles: any[];
}

export default function BottleGrid({ bottles }: BottleGridProps) {
    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, 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-4">
                    {/* 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 pb-2 scrollbar-hide">
                            <button
                                onClick={() => setSelectedCategory(null)}
                                className={`px-4 py-2 rounded-xl 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-4 py-2 rounded-xl 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 pb-2 scrollbar-hide">
                            <button
                                onClick={() => setSelectedDistillery(null)}
                                className={`px-4 py-2 rounded-xl 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-4 py-2 rounded-xl 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 pb-2 scrollbar-hide">
                            {['sealed', 'open', 'sampled', 'empty'].map((status) => (
                                <button
                                    key={status}
                                    onClick={() => setSelectedStatus(selectedStatus === status ? null : status)}
                                    className={`px-4 py-2 rounded-xl 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} />
                    ))}
                </div>
            ) : (
                <div className="text-center py-12">
                    <p className="text-zinc-500 italic">Keine Flaschen gefunden, die deinen Filtern entsprechen. 🔎</p>
                </div>
            )}
        </div>
    );
}
