'use client';

import React, { useEffect, useState, useCallback } from 'react';
import { getAllPendingBottles, deletePendingBottle, PendingBottle } from '@/lib/offline-db';
import { analyzeBottle } from '@/services/analyze-bottle';
import { saveBottle } from '@/services/save-bottle';
import { createClientComponentClient } from '@supabase/auth-helpers-nextjs';
import { RefreshCw, CheckCircle2, AlertCircle, Loader2 } from 'lucide-react';

export default function UploadQueue() {
    const supabase = createClientComponentClient();
    const [queue, setQueue] = useState<PendingBottle[]>([]);
    const [isSyncing, setIsSyncing] = useState(false);
    const [currentProgress, setCurrentProgress] = useState<{ id: string, status: string } | null>(null);

    const loadQueue = useCallback(async () => {
        const pending = await getAllPendingBottles();
        setQueue(pending);
    }, []);

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

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

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

        for (const item of queue) {
            setCurrentProgress({ id: item.id, status: 'Analysiere...' });
            try {
                // 1. Analyze
                const analysis = await analyzeBottle(item.imageBase64);
                if (analysis.success && analysis.data) {
                    setCurrentProgress({ id: item.id, status: 'Speichere...' });
                    // 2. Save
                    const save = await saveBottle(analysis.data, item.imageBase64, user.id);
                    if (save.success) {
                        await deletePendingBottle(item.id);
                    }
                }
            } catch (err) {
                console.error('Sync failed for item', item.id, err);
            }
        }

        setIsSyncing(false);
        setCurrentProgress(null);
        loadQueue();
    }, [isSyncing, queue, supabase, loadQueue]);

    useEffect(() => {
        loadQueue();

        // Listen for storage changes (e.g. from CameraCapture)
        const interval = setInterval(loadQueue, 5000);

        const handleOnline = () => {
            console.log('Back online! Triggering sync...');
            syncQueue();
        };

        window.addEventListener('online', handleOnline);
        return () => {
            clearInterval(interval);
            window.removeEventListener('online', handleOnline);
        };
    }, [loadQueue, syncQueue]);

    if (queue.length === 0) return null;

    return (
        <div className="fixed bottom-6 right-6 z-50 animate-in slide-in-from-right-10">
            <div className="bg-zinc-900 text-white p-4 rounded-2xl shadow-2xl border border-white/10 flex flex-col gap-3 min-w-[280px]">
                <div className="flex items-center justify-between border-b border-white/10 pb-2">
                    <div className="flex items-center gap-2">
                        <RefreshCw size={16} className={isSyncing ? 'animate-spin text-amber-500' : 'text-zinc-400'} />
                        <span className="text-xs font-black uppercase tracking-widest">Upload Queue</span>
                    </div>
                    <span className="bg-amber-600 text-[10px] font-black px-1.5 py-0.5 rounded-md">
                        {queue.length}
                    </span>
                </div>

                <div className="space-y-2">
                    {queue.slice(0, 3).map((item) => (
                        <div key={item.id} className="flex items-center justify-between text-[11px] font-medium text-zinc-400">
                            <div className="flex items-center gap-2">
                                <div className="w-6 h-6 rounded bg-zinc-800 overflow-hidden">
                                    <img src={item.imageBase64} className="w-full h-full object-cover opacity-50" />
                                </div>
                                <span className="truncate max-w-[120px]">
                                    {currentProgress?.id === item.id ? currentProgress.status : 'Wartet auf Netz...'}
                                </span>
                            </div>
                            {currentProgress?.id === item.id ? (
                                <Loader2 size={12} className="animate-spin text-amber-500" />
                            ) : (
                                <AlertCircle size={12} className="text-zinc-600" />
                            )}
                        </div>
                    ))}
                    {queue.length > 3 && (
                        <div className="text-[10px] text-zinc-500 text-center font-bold italic pt-1">
                            + {queue.length - 3} weitere Flaschen
                        </div>
                    )}
                </div>

                {navigator.onLine && !isSyncing && (
                    <button
                        onClick={syncQueue}
                        className="w-full py-2 bg-amber-600 hover:bg-amber-500 text-[10px] font-black uppercase rounded-lg transition-colors cursor-pointer"
                    >
                        Jetzt Synchronisieren
                    </button>
                )}
            </div>
        </div>
    );
}
