'use client';

import React, { useState, useMemo } from 'react';
import { Calendar, Star, ArrowUpDown, Clock, Trash2, Loader2 } from 'lucide-react';
import { deleteTasting } from '@/services/delete-tasting';

interface Tasting {
    id: string;
    rating: number;
    nose_notes?: string;
    palate_notes?: string;
    finish_notes?: string;
    is_sample?: boolean;
    bottle_id: string;
    created_at: string;
}

interface TastingListProps {
    initialTastings: Tasting[];
}

export default function TastingList({ initialTastings }: TastingListProps) {
    const [sortBy, setSortBy] = useState<'date-desc' | 'date-asc' | 'rating-desc' | 'rating-asc'>('date-desc');
    const [isDeleting, setIsDeleting] = useState<string | null>(null);

    const handleDelete = async (tastingId: string, bottleId: string) => {
        if (!confirm('Bist du sicher, dass du diese Notiz löschen möchtest?')) return;

        setIsDeleting(tastingId);
        try {
            const res = await deleteTasting(tastingId, bottleId);
            if (!res.success) {
                alert(res.error || 'Fehler beim Löschen');
            }
        } catch (err) {
            alert('Löschen fehlgeschlagen');
        } finally {
            setIsDeleting(null);
        }
    };

    const sortedTastings = useMemo(() => {
        const result = [...initialTastings];
        return result.sort((a, b) => {
            switch (sortBy) {
                case 'date-desc':
                    return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
                case 'date-asc':
                    return new Date(a.created_at).getTime() - new Date(b.created_at).getTime();
                case 'rating-desc':
                    return b.rating - a.rating;
                case 'rating-asc':
                    return a.rating - b.rating;
                default:
                    return 0;
            }
        });
    }, [initialTastings, sortBy]);

    if (!initialTastings || initialTastings.length === 0) {
        return (
            <div className="text-center py-12 bg-zinc-100 dark:bg-zinc-900/30 rounded-3xl border-2 border-dashed border-zinc-200 dark:border-zinc-800">
                <p className="text-zinc-400 italic font-medium">Noch keine Tasting Notes vorhanden. Zeit für ein Glas? 🥃</p>
            </div>
        );
    }

    return (
        <div className="space-y-6">
            <div className="flex justify-end">
                <div className="flex items-center gap-2 bg-zinc-100 dark:bg-zinc-900 p-1 rounded-xl border border-zinc-200 dark:border-zinc-800">
                    <ArrowUpDown size={14} className="ml-2 text-zinc-400" />
                    <select
                        value={sortBy}
                        onChange={(e) => setSortBy(e.target.value as any)}
                        className="bg-transparent border-none text-xs font-bold uppercase tracking-tight focus:ring-0 cursor-pointer pr-8 py-1.5 dark:text-zinc-300"
                    >
                        <option value="date-desc">Neueste zuerst</option>
                        <option value="date-asc">Älteste zuerst</option>
                        <option value="rating-desc">Beste Bewertung</option>
                        <option value="rating-asc">Niedrigste Bewertung</option>
                    </select>
                </div>
            </div>

            <div className="space-y-6">
                {sortedTastings.map((note) => (
                    <div
                        key={note.id}
                        className="bg-white dark:bg-zinc-900 p-6 rounded-3xl border border-zinc-200 dark:border-zinc-800 shadow-sm space-y-4 hover:border-amber-500/30 transition-all hover:shadow-md group"
                    >
                        <div className="flex justify-between items-center">
                            <div className="flex items-center gap-3">
                                <div className="bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 px-3 py-1.5 rounded-2xl text-sm font-black ring-1 ring-amber-500/20 flex items-center gap-1.5">
                                    <Star size={14} fill="currentColor" className="text-amber-500" />
                                    {note.rating}/100
                                </div>
                                <span className={`text-[10px] font-black px-2 py-0.5 rounded-lg uppercase tracking-tighter ${note.is_sample
                                    ? 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400'
                                    : 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400'
                                    }`}>
                                    {note.is_sample ? 'Sample' : 'Bottle'}
                                </span>
                                <div className="text-[10px] text-zinc-500 font-bold bg-zinc-100 dark:bg-zinc-800 px-2 py-1 rounded-lg flex items-center gap-1">
                                    <Clock size={10} />
                                    {new Date(note.created_at).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' })}
                                </div>
                            </div>
                            <div className="flex items-center gap-4">
                                <div className="text-[10px] text-zinc-400 font-black tracking-widest uppercase flex items-center gap-1">
                                    <Calendar size={12} />
                                    {new Date(note.created_at).toLocaleDateString('de-DE')}
                                </div>
                                <button
                                    onClick={() => handleDelete(note.id, note.bottle_id)}
                                    disabled={!!isDeleting}
                                    className="p-2 text-zinc-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-xl transition-all disabled:opacity-50"
                                    title="Tasting löschen"
                                >
                                    {isDeleting === note.id ? (
                                        <Loader2 size={14} className="animate-spin" />
                                    ) : (
                                        <Trash2 size={14} />
                                    )}
                                </button>
                            </div>
                        </div>

                        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 relative">
                            {/* Visual Divider for MD and up */}
                            <div className="hidden md:block absolute left-1/3 top-0 bottom-0 w-px bg-zinc-100 dark:bg-zinc-800/50" />
                            <div className="hidden md:block absolute left-2/3 top-0 bottom-0 w-px bg-zinc-100 dark:bg-zinc-800/50" />

                            {note.nose_notes && (
                                <div className="space-y-1">
                                    <div className="text-[10px] font-black text-zinc-400 uppercase tracking-widest mb-1">Nose</div>
                                    <p className="text-sm text-zinc-700 dark:text-zinc-300 leading-relaxed italic border-l-2 border-zinc-100 dark:border-zinc-800 pl-3">
                                        {note.nose_notes}
                                    </p>
                                </div>
                            )}
                            {note.palate_notes && (
                                <div className="space-y-1">
                                    <div className="text-[10px] font-black text-zinc-400 uppercase tracking-widest mb-1">Palate</div>
                                    <p className="text-sm text-zinc-700 dark:text-zinc-300 leading-relaxed italic border-l-2 border-zinc-100 dark:border-zinc-800 pl-3">
                                        {note.palate_notes}
                                    </p>
                                </div>
                            )}
                            {note.finish_notes && (
                                <div className="space-y-1">
                                    <div className="text-[10px] font-black text-zinc-400 uppercase tracking-widest mb-1">Finish</div>
                                    <p className="text-sm text-zinc-700 dark:text-zinc-300 leading-relaxed italic border-l-2 border-zinc-100 dark:border-zinc-800 pl-3">
                                        {note.finish_notes}
                                    </p>
                                </div>
                            )}
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
}
