'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();

    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} />
                            {t('grid.addSession')}
                        </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(locale === 'de' ? 'de-DE' : 'en-US')}
                        </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} />
                                    {t('grid.reviewRequired')}
                                </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 || t('grid.unknownBottle')}
                        </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">
                            {shortenCategory(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]">{t('grid.addedOn')}</span>
                        <span className="text-zinc-500 dark:text-zinc-300">
                            {new Date(bottle.created_at).toLocaleDateString(locale === 'de' ? 'de-DE' : 'en-US')}
                        </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 className="w-full space-y-8">
            {/* Search and Filters */}
            <div className="w-full max-w-6xl mx-auto px-4 space-y-4">
                <div className="flex flex-col md:flex-row gap-3">
                    <div className="relative flex-1 group">
                        <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-zinc-400 group-focus-within:text-amber-600 transition-colors" size={18} />
                        <input
                            type="text"
                            placeholder={t('grid.searchPlaceholder')}
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                            className="w-full pl-12 pr-12 py-3.5 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 rounded-[1.25rem] focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500/50 outline-none transition-all shadow-sm"
                        />
                        {searchQuery && (
                            <button
                                onClick={() => setSearchQuery('')}
                                className="absolute right-4 top-1/2 -translate-y-1/2 text-zinc-400 hover:text-amber-600 transition-colors"
                            >
                                <X size={18} />
                            </button>
                        )}
                    </div>

                    <div className="flex gap-3">
                        <select
                            value={sortBy}
                            onChange={(e) => setSortBy(e.target.value as any)}
                            className="flex-1 md:flex-none px-4 py-3.5 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 rounded-[1.25rem] text-sm font-bold focus:ring-2 focus:ring-amber-500/20 outline-none cursor-pointer appearance-none text-zinc-700 dark:text-zinc-300 shadow-sm"
                        >
                            <option value="created_at">{t('grid.sortBy.createdAt')}</option>
                            <option value="last_tasted">{t('grid.sortBy.lastTasted')}</option>
                            <option value="name">{t('grid.sortBy.name')}</option>
                        </select>

                        <button
                            onClick={() => setIsFiltersOpen(!isFiltersOpen)}
                            className={`px-5 py-3.5 rounded-[1.25rem] text-sm font-bold flex items-center gap-2 transition-all border shadow-sm ${isFiltersOpen || activeFiltersCount > 0
                                ? 'bg-amber-600 border-amber-600 text-white'
                                : 'bg-white dark:bg-zinc-900 border-zinc-200 dark:border-zinc-800 text-zinc-700 dark:text-zinc-300'
                                }`}
                        >
                            <Filter size={18} />
                            <span className="hidden sm:inline">{t('grid.filters')}</span>
                            {activeFiltersCount > 0 && (
                                <span className="bg-white text-amber-600 w-5 h-5 rounded-full flex items-center justify-center text-[10px] font-black">
                                    {activeFiltersCount}
                                </span>
                            )}
                        </button>
                    </div>
                </div>

                {/* Category Quick Filter (Always visible row) */}
                <div className="flex gap-2 overflow-x-auto pb-2 -mx-4 px-4 scrollbar-hide touch-pan-x">
                    <button
                        onClick={() => setSelectedCategory(null)}
                        className={`px-4 py-2 rounded-xl text-xs font-black whitespace-nowrap transition-all border ${selectedCategory === 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-500 hover:border-zinc-300'
                            }`}
                    >
                        {t('common.all').toUpperCase()}
                    </button>
                    {categories.map((cat) => (
                        <button
                            key={cat}
                            onClick={() => setSelectedCategory(selectedCategory === cat ? null : cat)}
                            className={`px-4 py-2 rounded-xl text-xs font-black 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-500 hover:border-zinc-300'
                                }`}
                        >
                            {shortenCategory(cat).toUpperCase()}
                        </button>
                    ))}
                </div>

                {/* Collapsible Advanced Filters */}
                {isFiltersOpen && (
                    <div className="p-6 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 rounded-[2rem] space-y-6 shadow-xl animate-in fade-in slide-in-from-top-4 duration-300">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div className="space-y-3">
                                <label className="text-[10px] font-black uppercase tracking-[0.2em] text-zinc-400 px-1">{t('grid.filter.distillery')}</label>
                                <div className="flex flex-wrap gap-2">
                                    <button
                                        onClick={() => setSelectedDistillery(null)}
                                        className={`px-3 py-1.5 rounded-xl text-[10px] font-black transition-all border ${selectedDistillery === null
                                            ? 'bg-zinc-900 dark:bg-white text-white dark:text-zinc-900'
                                            : 'bg-zinc-50 dark:bg-zinc-800 border-zinc-200 dark:border-zinc-700 text-zinc-500'
                                            }`}
                                    >
                                        {t('common.all').toUpperCase()}
                                    </button>
                                    {distilleries.map((dist) => (
                                        <button
                                            key={dist}
                                            onClick={() => setSelectedDistillery(selectedDistillery === dist ? null : dist)}
                                            className={`px-3 py-1.5 rounded-xl text-[10px] font-black transition-all border ${selectedDistillery === dist
                                                ? 'bg-amber-600 border-amber-600 text-white'
                                                : 'bg-zinc-50 dark:bg-zinc-800 border-zinc-200 dark:border-zinc-700 text-zinc-500'
                                                }`}
                                        >
                                            {dist.toUpperCase()}
                                        </button>
                                    ))}
                                </div>
                            </div>

                        </div>

                        <div className="pt-4 border-t border-zinc-100 dark:border-zinc-800 flex justify-between items-center">
                            <button
                                onClick={() => {
                                    setSelectedCategory(null);
                                    setSelectedDistillery(null);
                                    setSearchQuery('');
                                }}
                                className="text-[10px] font-black text-red-500 uppercase tracking-widest hover:underline"
                            >
                                {t('grid.resetAll')}
                            </button>
                            <button
                                onClick={() => setIsFiltersOpen(false)}
                                className="px-6 py-2 bg-zinc-900 dark:bg-white text-white dark:text-zinc-900 text-[10px] font-black rounded-xl 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>
    );
}
