'use client';

import { useEffect, useRef, useCallback } from 'react';
import { FEATURES } from '../config/features';
import { db } from '@/lib/db';
import { createClient } from '@/lib/supabase/client';
import { v4 as uuidv4 } from 'uuid';

/**
 * Upload processed image to Supabase and update bottle record
 */
async function uploadToSupabase(bottleId: string, blob: Blob): Promise<string | null> {
    try {
        const supabase = createClient();
        const { data: { user } } = await supabase.auth.getUser();

        if (!user) {
            console.warn('[ImageProcessor] No user session, skipping Supabase upload');
            return null;
        }

        // Upload to storage
        const fileName = `${user.id}/${bottleId}_nobg_${uuidv4()}.png`;
        const { error: uploadError } = await supabase.storage
            .from('bottles')
            .upload(fileName, blob, {
                contentType: 'image/png',
                upsert: true,
            });

        if (uploadError) {
            console.error('[ImageProcessor] Upload error:', uploadError);
            return null;
        }

        // Get public URL
        const { data: { publicUrl } } = supabase.storage
            .from('bottles')
            .getPublicUrl(fileName);

        // Update bottle record with new image URL
        const { error: updateError } = await supabase
            .from('bottles')
            .update({ image_url: publicUrl })
            .eq('id', bottleId);

        if (updateError) {
            console.error('[ImageProcessor] DB update error:', updateError);
            return null;
        }

        console.log(`[ImageProcessor] Uploaded to Supabase: ${bottleId}`);
        return publicUrl;
    } catch (err) {
        console.error('[ImageProcessor] Supabase sync failed:', err);
        return null;
    }
}

export function useImageProcessor() {
    const workerRef = useRef<Worker | null>(null);

    useEffect(() => {
        if (!FEATURES.ENABLE_AI_BG_REMOVAL) return;

        // Initialize worker
        console.log('[ImageProcessor] Initializing worker...');
        const worker = new Worker(
            '/bg-processor.worker.js',
            { type: 'module' }
        );
        workerRef.current = worker;
        console.log('[ImageProcessor] Worker instance created');

        worker.postMessage({ type: 'ping' });
        console.log('[ImageProcessor] Sent ping to worker');

        worker.onmessage = async (e) => {
            if (e.data.type === 'pong') {
                console.log('[ImageProcessor] Received pong from worker - Communication OK');
                return;
            }
            const { id, status, blob, error } = e.data;

            if (status === 'success' && blob) {
                // Convert blob to Base64 for IndexedDB storage
                const reader = new FileReader();
                reader.onloadend = async () => {
                    const base64data = reader.result as string;

                    try {
                        // Update cache_bottles if it exists there
                        const cachedBottle = await db.cache_bottles.get(id);
                        if (cachedBottle) {
                            await db.cache_bottles.update(id, {
                                image_url: base64data,
                                bgRemoved: true,
                                updated_at: new Date().toISOString()
                            });
                            console.log(`[ImageProcessor] Background removed for cached bottle: ${id}`);

                            // Upload to Supabase (fire and forget, don't block UI)
                            uploadToSupabase(id, blob).then(url => {
                                if (url) {
                                    // Update local cache with the new Supabase URL
                                    db.cache_bottles.update(id, { image_url: url });
                                }
                            });
                        }

                        // Update pending_scans if it exists there by temp_id
                        const pendingScan = await db.pending_scans.where('temp_id').equals(id).first();
                        if (pendingScan) {
                            await db.pending_scans.update(pendingScan.id!, {
                                imageBase64: base64data,
                                bgRemoved: true
                            });
                            console.log(`[ImageProcessor] Background removed for pending scan: ${id}`);
                        }
                    } catch (err) {
                        console.error('[ImageProcessor] Failed to update DB:', err);
                    }
                };
                reader.readAsDataURL(blob);
            } else if (status === 'error') {
                console.error('[ImageProcessor] Worker error:', error);
            }
        };

        return () => {
            worker.terminate();
        };
    }, []);

    const addToQueue = useCallback(async (id: string, imageBlob: Blob) => {
        if (!FEATURES.ENABLE_AI_BG_REMOVAL || !workerRef.current) {
            console.warn('[ImageProcessor] Background removal disabled or worker not ready');
            return;
        }

        // Check if already processed to avoid redundant work
        const cached = await db.cache_bottles.get(id);
        if (cached?.bgRemoved) return;

        const pending = await db.pending_scans.where('temp_id').equals(id).first();
        if (pending?.bgRemoved) return;

        workerRef.current.postMessage({ id, imageBlob });
    }, []);

    return { addToQueue };
}
