'use client';

import React, { useState, useMemo } from 'react';
import Link from 'next/link';
import { Search, Filter, X, Calendar, Clock, Package, FlaskConical, AlertCircle, Trash2, AlertTriangle, PlusCircle } from 'lucide-react';
import { getStorageUrl } from '@/lib/supabase';
import { useSearchParams } from 'next/navigation';
import { validateSession } from '@/services/validate-session';
import { useI18n } from '@/i18n/I18nContext';
import { useSession } from '@/context/SessionContext';
import { shortenCategory } from '@/lib/format';

interface Bottle {
    id: string;
    name: string;
    distillery: string;
    category: string;
    abv: number;
    age: number;
    image_url: string;
    purchase_price?: number | null;
    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 { t, locale } = useI18n();
    const imageUrl = getStorageUrl(bottle.image_url);

    return (
        <Link
            href={`/bottles/${bottle.id}${sessionId ? `?session_id=${sessionId}` : ''}`}
            className="block h-full group relative overflow-hidden rounded-2xl bg-zinc-900 border border-white/[0.05] transition-all duration-500 hover:border-orange-500/30 hover:shadow-2xl hover:shadow-orange-950/20 active:scale-[0.98]"
        >
            {/* === SPOTIFY-STYLE IMAGE SECTION === */}
            <div className="relative aspect-[3/4] overflow-hidden">

                {/* Layer 1: Blurred Backdrop */}
                <div className="absolute inset-0 z-0">
                    <img
                        src={imageUrl}
                        alt=""
                        loading="lazy"
                        className="w-full h-full object-cover scale-125 blur-[20px] saturate-150 brightness-[0.6]"
                    />
                    {/* Vignette Overlay */}
                    <div
                        className="absolute inset-0"
                        style={{
                            background: 'radial-gradient(circle, rgba(0,0,0,0) 20%, rgba(0,0,0,0.5) 80%)'
                        }}
                    />
                </div>

                {/* Layer 2: Sharp Foreground Image */}
                <div className="absolute inset-[10px] z-10 flex items-center justify-center">
                    <img
                        src={imageUrl}
                        alt={bottle.name}
                        loading="lazy"
                        className="max-w-full max-h-full object-contain drop-shadow-[0_10px_20px_rgba(0,0,0,0.5)] group-hover:scale-105 transition-transform duration-500 ease-out"
                    />
                </div>

                {/* Top Overlays */}
                {(bottle.is_whisky === false || (bottle.confidence && bottle.confidence < 70)) && (
                    <div className="absolute top-3 right-3 z-20">
                        <div className="bg-red-500 text-white p-1.5 rounded-full shadow-lg">
                            <AlertCircle size={12} />
                        </div>
                    </div>
                )}

                {sessionId && (
                    <div className="absolute top-3 left-3 z-20 bg-orange-600 text-white text-[9px] font-bold px-2 py-1 rounded-md flex items-center gap-1.5 shadow-xl">
                        <PlusCircle size={12} />
                        ADD
                    </div>
                )}

                {/* Bottom Gradient Overlay for Text */}
                <div
                    className="absolute bottom-0 left-0 right-0 z-10 h-32"
                    style={{
                        background: 'linear-gradient(to top, rgba(0,0,0,0.9) 0%, transparent 100%)'
                    }}
                />

                {/* Info Overlay at Bottom */}
                <div className="absolute bottom-0 left-0 right-0 z-20 p-4 text-white">
                    <p className="text-[10px] font-black text-orange-500 uppercase tracking-[0.2em] leading-none mb-1">
                        {bottle.distillery}
                    </p>
                    <h3 className="font-bold text-lg text-zinc-50 leading-tight tracking-tight line-clamp-2">
                        {bottle.name || t('grid.unknownBottle')}
                    </h3>

                    <div className="flex flex-wrap gap-2 mt-3">
                        <span className="px-2 py-1 bg-white/10 backdrop-blur-sm text-zinc-300 text-[9px] font-bold uppercase tracking-widest rounded-md">
                            {shortenCategory(bottle.category)}
                        </span>
                        <span className="px-2 py-1 bg-white/10 backdrop-blur-sm text-zinc-300 text-[9px] font-bold uppercase tracking-widest rounded-md">
                            {bottle.abv}% VOL
                        </span>
                    </div>
                </div>
            </div>
        </Link>
    );
}


interface BottleGridProps {
    bottles: any[];
}

export default function BottleGrid({ bottles }: BottleGridProps) {
    const { t } = useI18n();
    const { activeSession } = useSession();
    const searchParams = useSearchParams();
    const sessionIdFromUrl = searchParams.get('session_id');
    const effectiveSessionId = activeSession?.id || sessionIdFromUrl;

    const [validatedSessionId, setValidatedSessionId] = useState<string | null>(null);

    React.useEffect(() => {
        const checkSession = async () => {
            if (effectiveSessionId) {
                const isValid = await validateSession(effectiveSessionId);
                setValidatedSessionId(isValid ? effectiveSessionId : null);
            } else {
                setValidatedSessionId(null);
            }
        };
        checkSession();
    }, [effectiveSessionId]);

    const [searchQuery, setSearchQuery] = useState('');
    const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
    const [selectedDistillery, setSelectedDistillery] = 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(() => {
        const result = bottles.filter((bottle) => {
            const searchLower = searchQuery.toLowerCase();
            const tastingNotesMatch = bottle.tastings?.some((t: any) =>
                (t.nose_notes?.toLowerCase().includes(searchLower)) ||
                (t.palate_notes?.toLowerCase().includes(searchLower)) ||
                (t.finish_notes?.toLowerCase().includes(searchLower))
            );

            const matchesSearch =
                bottle.name.toLowerCase().includes(searchLower) ||
                bottle.distillery?.toLowerCase().includes(searchLower) ||
                bottle.category?.toLowerCase().includes(searchLower) ||
                tastingNotesMatch;

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

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

        // 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]);

    const [isFiltersOpen, setIsFiltersOpen] = useState(false);

    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">{t('home.noBottles')}</p>
            </div>
        );
    }

    const activeFiltersCount = (selectedCategory ? 1 : 0) + (selectedDistillery ? 1 : 0);

    return (
        <div id="collection" className="w-full space-y-8 scroll-mt-32">
            {/* Search and Filters - Minimalist Look */}
            <div id="search-filter" className="w-full max-w-6xl mx-auto px-4 space-y-6 scroll-mt-32">
                <div className="flex flex-col md:flex-row gap-4">
                    <div className="relative flex-1 group">
                        <Search className="absolute left-0 top-1/2 -translate-y-1/2 text-zinc-500 group-focus-within:text-orange-500 transition-colors" size={20} />
                        <input
                            type="text"
                            placeholder={t('grid.searchPlaceholder')}
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                            className="w-full pl-8 pr-8 py-4 bg-transparent border-b border-zinc-800 focus:border-orange-500 outline-none transition-all text-zinc-50 placeholder:text-zinc-500"
                        />
                        {searchQuery && (
                            <button
                                onClick={() => setSearchQuery('')}
                                className="absolute right-0 top-1/2 -translate-y-1/2 text-[#8F9096] hover:text-white transition-colors"
                            >
                                <X size={20} />
                            </button>
                        )}
                    </div>

                    <div className="flex gap-4 items-center">
                        <select
                            value={sortBy}
                            onChange={(e) => setSortBy(e.target.value as any)}
                            className="bg-transparent border-none text-zinc-500 text-xs font-bold uppercase tracking-widest outline-none cursor-pointer hover:text-white transition-colors appearance-none"
                        >
                            <option value="created_at" className="bg-zinc-950">{t('grid.sortBy.createdAt')}</option>
                            <option value="last_tasted" className="bg-zinc-950">{t('grid.sortBy.lastTasted')}</option>
                            <option value="name" className="bg-zinc-950">{t('grid.sortBy.name')}</option>
                        </select>

                        <button
                            onClick={() => setIsFiltersOpen(!isFiltersOpen)}
                            className={`flex items-center gap-2 text-xs font-bold uppercase tracking-widest transition-all ${isFiltersOpen || activeFiltersCount > 0
                                ? 'text-orange-500'
                                : 'text-zinc-500 hover:text-white'
                                }`}
                        >
                            <Filter size={18} />
                            <span className="hidden sm:inline">{t('grid.filters')}</span>
                            {activeFiltersCount > 0 && (
                                <span className="bg-orange-600 text-white w-4 h-4 rounded-full flex items-center justify-center text-[8px] font-bold">
                                    {activeFiltersCount}
                                </span>
                            )}
                        </button>
                    </div>
                </div>

                {/* Category Quick Filter - Flat Chips */}
                <div className="flex gap-3 overflow-x-auto pb-2 -mx-4 px-4 scrollbar-hide touch-pan-x">
                    <button
                        onClick={() => setSelectedCategory(null)}
                        className={`px-4 py-2 rounded-full text-[10px] font-bold uppercase tracking-widest whitespace-nowrap transition-all border ${selectedCategory === null
                            ? 'bg-orange-600 border-orange-600 text-white'
                            : 'bg-zinc-900 border-zinc-800 text-zinc-400 hover:border-zinc-700'
                            }`}
                    >
                        {t('common.all')}
                    </button>
                    {categories.map((cat) => (
                        <button
                            key={cat}
                            onClick={() => setSelectedCategory(selectedCategory === cat ? null : cat)}
                            className={`px-4 py-2 rounded-full text-[10px] font-bold uppercase tracking-widest whitespace-nowrap transition-all border ${selectedCategory === cat
                                ? 'bg-orange-600 border-orange-600 text-white'
                                : 'bg-zinc-900 border-zinc-800 text-zinc-400 hover:border-zinc-700'
                                }`}
                        >
                            {shortenCategory(cat)}
                        </button>
                    ))}
                </div>

                {/* Collapsible Advanced Filters - Industrial Overlay */}
                {isFiltersOpen && (
                    <div className="p-8 bg-zinc-900 border border-zinc-800 rounded-2xl space-y-8 animate-in fade-in slide-in-from-top-4 duration-500">
                        <div className="space-y-4">
                            <label className="text-[10px] font-bold uppercase tracking-[0.2em] text-zinc-500">{t('grid.filter.distillery')}</label>
                            <div className="flex flex-wrap gap-2">
                                <button
                                    onClick={() => setSelectedDistillery(null)}
                                    className={`px-4 py-2 rounded-full text-[10px] font-bold uppercase tracking-widest transition-all border ${selectedDistillery === null
                                        ? 'bg-orange-600 border-orange-600 text-white'
                                        : 'bg-zinc-800 border-zinc-700 text-zinc-400'
                                        }`}
                                >
                                    {t('common.all')}
                                </button>
                                {distilleries.map((dist) => (
                                    <button
                                        key={dist}
                                        onClick={() => setSelectedDistillery(selectedDistillery === dist ? null : dist)}
                                        className={`px-4 py-2 rounded-full text-[10px] font-bold uppercase tracking-widest transition-all border ${selectedDistillery === dist
                                            ? 'bg-orange-600 border-orange-600 text-white'
                                            : 'bg-zinc-800 border-zinc-700 text-zinc-400'
                                            }`}
                                    >
                                        {dist}
                                    </button>
                                ))}
                            </div>
                        </div>

                        <div className="pt-6 border-t border-zinc-800 flex justify-between items-center">
                            <button
                                onClick={() => {
                                    setSelectedCategory(null);
                                    setSelectedDistillery(null);
                                    setSearchQuery('');
                                }}
                                className="text-[10px] font-bold text-red-500 uppercase tracking-widest hover:text-red-400"
                            >
                                {t('grid.resetAll')}
                            </button>
                            <button
                                onClick={() => setIsFiltersOpen(false)}
                                className="px-8 py-3 bg-zinc-50 text-zinc-950 text-[10px] font-bold rounded-full uppercase tracking-widest transition-transform active:scale-95"
                            >
                                {t('grid.close')}
                            </button>
                        </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={validatedSessionId} />
                    ))}
                </div>
            ) : (
                <div className="text-center py-12">
                    <p className="text-zinc-500 italic">{t('grid.noResults')}</p>
                </div>
            )}
        </div>
    );
}
