'use client';

import React from 'react';
import { CheckCircle2, AlertTriangle, Clock, Droplets, Info } from 'lucide-react';
import Link from 'next/link';

interface TimelineTasting {
    id: string;
    bottle_id: string;
    bottle_name: string;
    tasted_at: string;
    rating: number;
    tags: string[];
    category?: string;
}

interface SessionTimelineProps {
    tastings: TimelineTasting[];
    sessionStart?: string;
    isBlind?: boolean;
    isRevealed?: boolean;
}

// Keywords that indicate a "Peat Bomb"
const SMOKY_KEYWORDS = ['rauch', 'torf', 'smoke', 'peat', 'islay', 'ash', 'lagerfeuer', 'campfire', 'asphalte'];

export default function SessionTimeline({ tastings, sessionStart, isBlind, isRevealed }: SessionTimelineProps) {
    if (!tastings || tastings.length === 0) {
        return (
            <div className="p-8 text-center bg-zinc-50 dark:bg-zinc-900/50 rounded-3xl border border-dashed border-zinc-200 dark:border-zinc-800">
                <Clock size={32} className="mx-auto text-zinc-300 mb-3" />
                <p className="text-zinc-500 text-sm font-medium italic">Noch keine Dram-Historie vorhanden.</p>
            </div>
        );
    }

    // Sort by tasted_at
    const sortedTastings = [...tastings].sort((a, b) =>
        new Date(a.tasted_at).getTime() - new Date(b.tasted_at).getTime()
    );

    const firstTastingTime = sessionStart ? new Date(sessionStart).getTime() : new Date(sortedTastings[0].tasted_at).getTime();

    const checkIsSmoky = (tasting: TimelineTasting) => {
        const textToSearch = (tasting.tags.join(' ') + ' ' + (tasting.category || '')).toLowerCase();
        return SMOKY_KEYWORDS.some(keyword => textToSearch.includes(keyword));
    };

    return (
        <div className="relative pl-6 space-y-6 before:absolute before:inset-0 before:left-[9px] before:w-[2px] before:bg-zinc-200 dark:before:bg-zinc-800 before:h-full mb-12">
            {sortedTastings.map((tasting, index) => {
                const tastedDate = new Date(tasting.tasted_at);
                const currentTime = tastedDate.getTime();
                const diffMinutes = Math.round((currentTime - firstTastingTime) / (1000 * 60));
                const wallClockTime = tastedDate.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' });

                // Blind Mode logic
                const showDetails = !isBlind || isRevealed;
                const displayName = showDetails ? tasting.bottle_name : `Sample ${String.fromCharCode(65 + index)}`;
                const isSmoky = checkIsSmoky(tasting);

                const wasPreviousSmoky = index > 0 && checkIsSmoky(sortedTastings[index - 1]);
                const timeSinceLastDram = index > 0
                    ? Math.round((currentTime - new Date(sortedTastings[index - 1].tasted_at).getTime()) / (1000 * 60))
                    : 0;

                return (
                    <div key={tasting.id} className="relative group">
                        {/* Dot */}
                        <div className={`absolute -left-[22px] top-4 w-5 h-5 rounded-full border-[3px] border-zinc-950 shadow-sm z-10 flex items-center justify-center ${isSmoky && showDetails ? 'bg-orange-600' : 'bg-zinc-600'}`}>
                            {isSmoky && showDetails && <Droplets size={8} className="text-white fill-white" />}
                        </div>

                        <div className="bg-zinc-900 p-4 rounded-2xl border border-zinc-800 shadow-sm hover:shadow-md transition-shadow group-hover:border-orange-500/30">
                            <div className="flex justify-between items-start gap-3">
                                <div className="min-w-0">
                                    <div className="flex items-center gap-2 mb-1">
                                        <span className="text-[10px] font-bold text-orange-600 uppercase tracking-widest leading-none">Dram #{index + 1}</span>
                                        <span className="text-[10px] font-bold text-zinc-500 uppercase tracking-tight leading-none">
                                            {wallClockTime} ({index === 0 ? 'Start' : `+${diffMinutes}m`})
                                        </span>
                                        {isSmoky && showDetails && (
                                            <span className="bg-orange-900/40 text-orange-500 text-[8px] font-bold px-1.5 py-0.5 rounded-md uppercase tracking-tighter border border-orange-500/20">Peat Bomb</span>
                                        )}
                                    </div>

                                    {showDetails ? (
                                        <Link
                                            href={`/bottles/${tasting.bottle_id}`}
                                            className="text-sm font-bold text-zinc-100 hover:text-orange-600 truncate block mt-0.5 uppercase tracking-tight"
                                        >
                                            {displayName}
                                        </Link>
                                    ) : (
                                        <div className="text-sm font-bold text-zinc-100 bg-zinc-800/30 blur-[4px] px-2 py-0.5 rounded-md select-none">
                                            Unknown Bottle
                                        </div>
                                    )}

                                    {!showDetails && (
                                        <div className="mt-1 text-purple-500 font-black uppercase text-[12px] tracking-tight">
                                            {displayName}
                                        </div>
                                    )}

                                    <div className="mt-2 flex flex-wrap gap-1">
                                        {showDetails ? (
                                            tasting.tags.slice(0, 2).map(tag => (
                                                <span key={tag} className="text-[9px] text-zinc-500 bg-zinc-800/50 px-2 py-0.5 rounded-full border border-zinc-800">
                                                    {tag}
                                                </span>
                                            ))
                                        ) : (
                                            <span className="text-[9px] text-zinc-600 bg-zinc-900 px-2 py-0.5 rounded-full border border-zinc-800 italic">
                                                Noten versteckt...
                                            </span>
                                        )}
                                    </div>
                                </div>
                                <div className="shrink-0 flex flex-col items-end">
                                    <div className="text-lg font-bold text-zinc-50 leading-none">
                                        {showDetails ? tasting.rating : '?'}
                                    </div>
                                    <div className="text-[9px] font-bold text-zinc-500 uppercase tracking-tighter mt-1">Punkte</div>
                                </div>
                            </div>

                            {wasPreviousSmoky && timeSinceLastDram < 20 && showDetails && (
                                <div className="mt-4 p-2 bg-orange-900/10 border border-orange-900/30 rounded-xl flex items-center gap-2 animate-in slide-in-from-top-1">
                                    <AlertTriangle size={12} className="text-orange-600 shrink-0" />
                                    <p className="text-[9px] text-orange-400 font-bold leading-tight">
                                        Achtung: Gaumen war noch torf-belegt (nur {timeSinceLastDram}m Abstand).
                                    </p>
                                </div>
                            )}
                        </div>
                    </div>
                );
            })}
        </div>
    );
}
