'use client';

import React, { useEffect, useState, useCallback } from 'react';
import { useLiveQuery } from 'dexie-react-hooks';
import { db, PendingScan, PendingTasting } from '@/lib/db';
import { magicScan } from '@/services/magic-scan';
import { saveBottle } from '@/services/save-bottle';
import { saveTasting } from '@/services/save-tasting';
import { createClient } from '@/lib/supabase/client';
import { RefreshCw, CheckCircle2, AlertCircle, Loader2, Info, Send } from 'lucide-react';
import TastingNoteForm from './TastingNoteForm';

export default function UploadQueue() {
    const supabase = createClient();
    const [isSyncing, setIsSyncing] = useState(false);
    const [currentProgress, setCurrentProgress] = useState<{ id: string, status: string } | null>(null);
    const [isCollapsed, setIsCollapsed] = useState(false);
    const [completedItems, setCompletedItems] = useState<{ id: string; name: string; bottleId?: string; type: 'scan' | 'tasting' }[]>([]);
    const [activeNoteScanId, setActiveNoteScanId] = useState<string | null>(null);

    const pendingScans = useLiveQuery(() => db.pending_scans.toArray(), [], [] as PendingScan[]);
    const pendingTastings = useLiveQuery(() => db.pending_tastings.toArray(), [], [] as PendingTasting[]);

    const totalInQueue = pendingScans.length + pendingTastings.length;

    const syncQueue = useCallback(async () => {
        if (isSyncing || !navigator.onLine || totalInQueue === 0) return;

        setIsSyncing(true);
        const { data: { user } } = await supabase.auth.getUser();

        if (!user) {
            console.error('No user found for background sync');
            setIsSyncing(false);
            return;
        }

        try {
            // 1. Sync Scans (Magic Shots)
            for (const item of pendingScans) {
                const itemId = `scan-${item.id}`;
                setCurrentProgress({ id: itemId, status: 'Analysiere Scan...' });
                try {
                    const analysis = await magicScan(item.imageBase64, item.provider, item.locale);
                    if (analysis.success && analysis.data) {
                        const bottleData = analysis.data;
                        setCurrentProgress({ id: itemId, status: 'Speichere Flasche...' });
                        const save = await saveBottle(bottleData, item.imageBase64, user.id);
                        if (save.success && save.data) {
                            const newBottleId = save.data.id;

                            // Reconcile pending tastings linked to this temp_id
                            if (item.temp_id) {
                                const linkedTastings = await db.pending_tastings
                                    .where('pending_bottle_id')
                                    .equals(item.temp_id)
                                    .toArray();

                                for (const lt of linkedTastings) {
                                    await db.pending_tastings.update(lt.id!, {
                                        bottle_id: newBottleId,
                                        pending_bottle_id: undefined
                                    });
                                }
                            }

                            setCompletedItems(prev => [...prev.slice(-4), {
                                id: itemId,
                                name: bottleData.name || 'Unbekannter Whisky',
                                bottleId: newBottleId,
                                type: 'scan'
                            }]);
                            await db.pending_scans.delete(item.id!);
                        }
                    } else {
                        throw new Error(analysis.error || 'Analyse fehlgeschlagen');
                    }
                } catch (err) {
                    console.error('Scan sync failed:', err);
                    setCurrentProgress({ id: itemId, status: 'Fehler bei Scan' });
                    // Wait a bit before next
                    await new Promise(r => setTimeout(r, 2000));
                }
            }

            // 2. Sync Tastings
            for (const item of pendingTastings) {
                // If it still has a pending_bottle_id, it means the scan hasn't synced yet.
                // We SKIP this tasting and wait for the scan to finish in a future loop.
                if (item.pending_bottle_id) {
                    continue;
                }

                const itemId = `tasting-${item.id}`;
                setCurrentProgress({ id: itemId, status: 'Synchronisiere Tasting...' });
                try {
                    const result = await saveTasting({
                        ...item.data,
                        is_sample: item.data.is_sample ?? false,
                        bottle_id: item.bottle_id as string,
                        tasted_at: item.tasted_at
                    });
                    if (result.success) {
                        setCompletedItems(prev => [...prev.slice(-4), {
                            id: itemId,
                            name: 'Tasting Note',
                            bottleId: item.bottle_id,
                            type: 'tasting'
                        }]);
                        await db.pending_tastings.delete(item.id!);
                    } else {
                        throw new Error(result.error);
                    }
                } catch (err) {
                    console.error('Tasting sync failed:', err);
                    setCurrentProgress({ id: itemId, status: 'Fehler bei Tasting' });
                    await new Promise(r => setTimeout(r, 2000));
                }
            }
        } catch (err) {
            console.error('Global Sync Error:', err);
        } finally {
            setIsSyncing(false);
            setCurrentProgress(null);
        }
    }, [isSyncing, pendingScans, pendingTastings, totalInQueue, supabase]);

    useEffect(() => {
        const handleOnline = () => {
            console.log('Online! Triggering background sync...');
            syncQueue();
        };

        window.addEventListener('online', handleOnline);

        // Initial check if we are online and have items
        if (navigator.onLine && totalInQueue > 0 && !isSyncing) {
            syncQueue();
        }

        return () => window.removeEventListener('online', handleOnline);
    }, [totalInQueue, syncQueue, isSyncing]);

    if (totalInQueue === 0) return null;

    return (
        <div className={`fixed bottom-6 left-1/2 -translate-x-1/2 md:left-auto md:translate-x-0 md:right-6 z-[100] animate-in slide-in-from-bottom-10 md:slide-in-from-right-10 w-[calc(100%-2rem)] md:w-auto`}>
            <div className="bg-zinc-900 border border-white/10 rounded-3xl shadow-2xl overflow-hidden transition-all duration-500">
                {/* Header */}
                <div
                    className="p-4 bg-zinc-800/50 flex items-center justify-between cursor-pointer"
                    onClick={() => setIsCollapsed(!isCollapsed)}
                >
                    <div className="flex items-center gap-3">
                        <div className="relative">
                            <RefreshCw size={18} className={isSyncing ? 'animate-spin text-amber-500' : 'text-zinc-500'} />
                            {totalInQueue > 0 && !isSyncing && (
                                <div className="absolute -top-1 -right-1 w-2 h-2 bg-amber-500 rounded-full animate-pulse" />
                            )}
                        </div>
                        <div className="flex flex-col">
                            <span className="text-[10px] font-black uppercase tracking-[0.2em] text-zinc-400">Sync Warteschlange</span>
                            <span className="text-xs font-bold text-white">
                                {isSyncing ? 'Synchronisiere...' : navigator.onLine ? 'Warten auf Upload' : 'Offline - Lokal gespeichert'}
                            </span>
                        </div>
                    </div>
                    <div className="flex items-center gap-2">
                        <span className="bg-amber-600 text-[10px] font-black px-2 py-0.5 rounded-full text-white">
                            {totalInQueue}
                        </span>
                    </div>
                </div>

                {/* Content */}
                {!isCollapsed && (
                    <div className="p-4 space-y-4 max-h-[400px] overflow-y-auto custom-scrollbar">
                        <div className="space-y-3">
                            {/* Completed Items (The "Results") */}
                            {completedItems.length > 0 && (
                                <div className="space-y-2 pb-2 border-b border-white/5">
                                    <div className="flex items-center gap-2 text-[9px] font-black uppercase tracking-[0.2em] text-green-500 mb-2">
                                        <CheckCircle2 size={10} />
                                        Synchronisierte Items
                                    </div>
                                    {completedItems.map((item) => (
                                        <div key={`done-${item.id}`} className="flex items-center justify-between p-2 rounded-xl bg-green-500/10 border border-green-500/20 animate-in zoom-in-95">
                                            <div className="flex flex-col gap-0.5 min-w-0">
                                                <span className="text-[10px] font-black text-green-500 uppercase tracking-widest">
                                                    {item.type === 'scan' ? 'Neu im Vault' : 'Tasting gespeichert'}
                                                </span>
                                                <span className="text-[11px] font-bold text-white truncate pr-2">
                                                    {item.name}
                                                </span>
                                            </div>
                                            {item.bottleId && (
                                                <a
                                                    href={`/bottles/${item.bottleId}`}
                                                    className="shrink-0 px-3 py-1.5 bg-green-500 hover:bg-green-600 text-white text-[10px] font-black uppercase rounded-lg transition-all shadow-lg shadow-green-500/20 flex items-center gap-1"
                                                >
                                                    Ansehen
                                                    <CheckCircle2 size={10} />
                                                </a>
                                            )}
                                        </div>
                                    ))}
                                </div>
                            )}

                            {/* Scans */}
                            {pendingScans.map((item) => (
                                <div key={`scan-${item.id}`} className="flex flex-col gap-2 p-2 rounded-xl bg-white/5 border border-white/5 transition-colors">
                                    <div className="flex items-center justify-between">
                                        <div className="flex items-center gap-3">
                                            <div className="w-10 h-10 rounded-lg bg-zinc-800 overflow-hidden ring-1 ring-white/10 shrink-0">
                                                <img src={item.imageBase64} className="w-full h-full object-cover opacity-60" />
                                            </div>
                                            <div className="flex flex-col gap-0.5">
                                                <span className="text-[10px] font-black text-amber-500/80 uppercase tracking-widest">Magic Shot</span>
                                                <span className="text-[11px] font-medium text-zinc-300">
                                                    {currentProgress?.id === `scan-${item.id}` ? (
                                                        <span className="flex items-center gap-1.5">
                                                            <Loader2 size={10} className="animate-spin" />
                                                            {currentProgress.status}
                                                        </span>
                                                    ) : 'Wartet auf Verbindung...'}
                                                </span>
                                            </div>
                                        </div>
                                        <div className="text-[9px] text-zinc-500 font-bold whitespace-nowrap ml-4">
                                            {new Date(item.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                                        </div>
                                    </div>

                                    {/* Link for adding tasting notes to pending scan */}
                                    <button
                                        onClick={() => setActiveNoteScanId(activeNoteScanId === item.temp_id ? null : item.temp_id)}
                                        className="w-full py-2 bg-amber-600/10 hover:bg-amber-600/20 text-amber-500 text-[10px] font-black uppercase rounded-lg transition-all flex items-center justify-center gap-2 border border-amber-500/10"
                                    >
                                        <Send size={10} />
                                        {activeNoteScanId === item.temp_id ? 'Abbrechen' : 'Notiz hinzufügen'}
                                    </button>

                                    {activeNoteScanId === item.temp_id && (
                                        <div className="mt-2 p-4 bg-zinc-800 rounded-2xl border border-white/5 animate-in slide-in-from-top-2">
                                            <TastingNoteForm
                                                pendingBottleId={item.temp_id}
                                                onSuccess={() => setActiveNoteScanId(null)}
                                            />
                                        </div>
                                    )}
                                </div>
                            ))}

                            {/* Tastings */}
                            {pendingTastings.map((item) => (
                                <div key={`tasting-${item.id}`} className="group flex items-center justify-between p-2 rounded-xl bg-white/5 border border-white/5 hover:bg-white/10 transition-colors">
                                    <div className="flex items-center gap-3">
                                        <div className="w-10 h-10 rounded-lg bg-amber-900/20 flex items-center justify-center ring-1 ring-amber-500/20 shrink-0">
                                            <div className="text-sm font-black text-amber-500">{item.data.rating}</div>
                                        </div>
                                        <div className="flex flex-col gap-0.5">
                                            <span className="text-[10px] font-black text-amber-500/80 uppercase tracking-widest">
                                                {item.pending_bottle_id ? 'Draft Notiz' : 'Tasting Note'}
                                            </span>
                                            <span className="text-[11px] font-medium text-zinc-300">
                                                {item.pending_bottle_id ? (
                                                    <span className="text-amber-500/60 italic">Wartet auf Scan...</span>
                                                ) : currentProgress?.id === `tasting-${item.id}` ? (
                                                    <span className="flex items-center gap-1.5">
                                                        <Loader2 size={10} className="animate-spin" />
                                                        {currentProgress.status}
                                                    </span>
                                                ) : 'Wartet auf Sync...'}
                                            </span>
                                        </div>
                                    </div>
                                    <div className="text-[9px] text-zinc-500 font-bold whitespace-nowrap ml-4">
                                        {new Date(item.tasted_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                                    </div>
                                </div>
                            ))}
                        </div>

                        {navigator.onLine && !isSyncing && (
                            <button
                                onClick={() => syncQueue()}
                                className="w-full py-3 bg-white/5 hover:bg-white/10 text-amber-500 text-[10px] font-black uppercase rounded-2xl transition-all border border-white/5 active:scale-95 flex items-center justify-center gap-2 mt-2"
                            >
                                <RefreshCw size={12} />
                                Synchronisierung erzwingen
                            </button>
                        )}

                        {!navigator.onLine && (
                            <div className="flex items-center justify-center gap-2 py-2 text-[10px] text-zinc-500 font-bold italic">
                                <AlertCircle size={12} />
                                Keine Internetverbindung
                            </div>
                        )}
                    </div>
                )}
            </div>
        </div>
    );
}

