import { useCallback } from 'react';
import { useShallow } from 'zustand/react/shallow';
import { useProjectStore } from '@lib/store/project';
import { useCanvasContext } from '../CanvasContext';
import { GenerationRecord } from '@/types';

export const useAssetSaver = () => {
    const { addAsset, storeUpdateAsset, storeUpdateStoryboard, assets, storyboards } = useProjectStore(
        useShallow((s) => ({
            addAsset: s.addAsset,
            storeUpdateAsset: s.updateAsset,
            storeUpdateStoryboard: s.updateStoryboard,
            assets: s.assets,
            storyboards: s.storyboards,
        }))
    );
    const { initialAssetId, initialStoryboardId, onUpdateAsset, onUpdateStoryboard } = useCanvasContext();

    const saveAsset = useCallback((
        type: 'image' | 'video' | 'audio', 
        src: string, 
        title: string, 
        metadata?: any,
        context?: {
            assetId?: string | null;
            storyboardId?: string | null;
        }
    ) => {
        const timestamp = Date.now();
        const genId = `gen-${timestamp}-${Math.random().toString(36).substr(2, 9)}`;

        const generationRecord: GenerationRecord = {
            id: genId,
            timestamp,
            status: 'success' as const,
            model: metadata?.model || 'canvas-generation',
            prompt: metadata?.prompt || title,
            resultUrl: src,
            type: type === 'audio' ? 'image' : type as any, 
            params: metadata?.params || {}
        } as GenerationRecord;

        // Determine target IDs (prefer explicit context over initial context)
        // Note: We check for undefined because null is a valid "no-op" value from context
        const targetAssetId = (context && context.assetId !== undefined) ? context.assetId : initialAssetId;
        const targetStoryboardId = (context && context.storyboardId !== undefined) ? context.storyboardId : initialStoryboardId;

        // 1. Update Asset if present
        if (targetAssetId) {
            const asset = assets.find(a => a.id === targetAssetId);
            if (asset) {
                const currentUrls = type === 'video' ? (asset.videoUrls || []) : (asset.imageUrls || []);
                const isVideo = type === 'video';
                
                // Avoid duplicates
                if (!currentUrls.includes(src)) {
                     const updates: any = {
                         generations: [generationRecord, ...(asset.generations || [])]
                     };
                     if (isVideo) {
                         updates.videoUrls = [src, ...currentUrls];
                     } else {
                         updates.imageUrls = [src, ...currentUrls];
                     }
                     if (onUpdateAsset) {
                         onUpdateAsset(targetAssetId, updates);
                     } else {
                         storeUpdateAsset(targetAssetId, updates);
                     }
                }
                return; 
            }
        }

        // 2. Update Storyboard if present
        if (targetStoryboardId) {
            const storyboard = storyboards.find(s => s.id === targetStoryboardId);
            if (storyboard) {
                const currentUrls = type === 'video' ? (storyboard.videoUrls || []) : (storyboard.imageUrls || []);
                const isVideo = type === 'video';
                
                if (!currentUrls.includes(src)) {
                    const updates: any = {
                         generations: [generationRecord, ...(storyboard.generations || [])]
                    };
                    if (isVideo) {
                        updates.videoUrls = [src, ...currentUrls];
                    } else {
                        updates.imageUrls = [src, ...currentUrls];
                    }
                    if (onUpdateStoryboard) {
                        onUpdateStoryboard(targetStoryboardId, updates);
                    } else {
                        storeUpdateStoryboard(targetStoryboardId, updates);
                    }
                }
                return;
            }
        }

        // 3. Fallback: Create New Asset
        addAsset({
            id: crypto.randomUUID(),
            type: type === 'audio' ? 'other' : 'scene',
            name: title,
            desc: metadata?.prompt || 'Generated from Canvas',
            tags: ['canvas-generated'],
            imageUrl: type === 'image' ? src : undefined,
            videoUrls: type === 'video' ? [src] : undefined,
            generations: [generationRecord]
        });

    }, [addAsset, storeUpdateAsset, storeUpdateStoryboard, assets, storyboards, initialAssetId, initialStoryboardId, onUpdateAsset, onUpdateStoryboard]);

    return { saveAsset };
};
