import { useState, useCallback } from 'react'; import { toast } from '@/components/ui/use-toast'; /** * Default generation options (Gemini Imagen) */ export interface GenerationDefaults { aspectRatio: string; imageSize: string; } /** * Props for the useImageGenerationDialog hook */ interface UseImageGenerationDialogProps { contentSource: string; generationApiEndpoint: string; generationDefaults: GenerationDefaults; } /** * Return type for the hook */ interface UseImageGenerationDialogReturn { generateImageDialogOpen: boolean; setGenerateImageDialogOpen: React.Dispatch>; dialogStep: 'selectPrompt' | 'configureOptions'; loadingPrompts: boolean; availablePrompts: string[]; dialogSelectedPrompt: string; isGeneratingImage: boolean; generationError: string | null; generationSuccess: boolean; generatedImageUrl: string | null; openDialog: () => void; handleDialogPromptSelect: (prompt: string) => void; handleGoToOptions: () => void; handleGoBackToPromptSelect: () => void; triggerImageGeneration: (options: { prompt: string; aspectRatio: string; imageSize: string }) => Promise; } /** * Simplified hook for image generation using Gemini Imagen API * No polling needed - synchronous API call */ export function useImageGenerationDialog({ contentSource, generationApiEndpoint, generationDefaults, }: UseImageGenerationDialogProps): UseImageGenerationDialogReturn { // Dialog state const [generateImageDialogOpen, setGenerateImageDialogOpen] = useState(false); const [dialogStep, setDialogStep] = useState<'selectPrompt' | 'configureOptions'>('selectPrompt'); const [availablePrompts, setAvailablePrompts] = useState([]); const [dialogSelectedPrompt, setDialogSelectedPrompt] = useState(''); const [loadingPrompts, setLoadingPrompts] = useState(false); // Generation state const [isGeneratingImage, setIsGeneratingImage] = useState(false); const [generationError, setGenerationError] = useState(null); const [generationSuccess, setGenerationSuccess] = useState(false); const [generatedImageUrl, setGeneratedImageUrl] = useState(null); // Dialog flow handlers const handleDialogPromptSelect = (prompt: string) => { setDialogSelectedPrompt(prompt); }; const handleGoToOptions = () => { if (dialogSelectedPrompt) { setDialogStep('configureOptions'); setGenerationError(null); } else { toast({ title: "Error", description: "Please select a prompt first.", variant: "destructive" }); } }; const handleGoBackToPromptSelect = () => { setDialogStep('selectPrompt'); setIsGeneratingImage(false); setGenerationError(null); setGenerationSuccess(false); setGeneratedImageUrl(null); }; // Fetch prompts from API const fetchPrompts = useCallback(async () => { setLoadingPrompts(true); setGenerationError(null); setAvailablePrompts([]); setDialogSelectedPrompt(''); const sourceText = contentSource || "Generate creative image prompts"; try { console.log("[useImageGenerationDialog] Fetching prompts for content:", sourceText.substring(0, 100) + "..."); const response = await fetch('/api/admin/generate-prompts', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ content: sourceText }) }); const data = await response.json(); if (!response.ok) { throw new Error(data.error || `API Error: ${response.statusText}`); } if (!data.prompts || !Array.isArray(data.prompts) || data.prompts.length === 0) { console.warn('[useImageGenerationDialog] API returned no valid prompts.'); setAvailablePrompts([]); } else { console.log("[useImageGenerationDialog] Received prompts:", data.prompts); setAvailablePrompts(data.prompts); if (data.prompts.length > 0) { setDialogSelectedPrompt(data.prompts[0]); } } } catch (error) { const errorMessage = error instanceof Error ? error.message : "Failed to fetch prompts."; console.error("[useImageGenerationDialog] Error fetching prompts:", errorMessage); setGenerationError(errorMessage); toast({ title: 'Error Fetching Prompts', description: `${errorMessage}. You can still type your own prompt.`, variant: 'destructive' }); setAvailablePrompts([]); } finally { setLoadingPrompts(false); } }, [contentSource]); // Open dialog and fetch prompts const openDialog = useCallback(() => { setDialogStep('selectPrompt'); setAvailablePrompts([]); setDialogSelectedPrompt(''); setGenerationError(null); setGenerationSuccess(false); setGeneratedImageUrl(null); setIsGeneratingImage(false); fetchPrompts(); setGenerateImageDialogOpen(true); }, [fetchPrompts]); // Trigger image generation - synchronous API call (Gemini Imagen) const triggerImageGeneration = useCallback(async (options: { prompt: string; aspectRatio: string; imageSize: string }) => { setIsGeneratingImage(true); setGenerationError(null); setGenerationSuccess(false); setGeneratedImageUrl(null); console.log("[useImageGenerationDialog] Generating image with Gemini Imagen:", options); try { const response = await fetch(generationApiEndpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt: options.prompt, aspectRatio: options.aspectRatio, imageSize: options.imageSize, }) }); const data = await response.json(); if (!response.ok || data.error) { throw new Error(data.error || data.details || `API Error: ${response.statusText}`); } if (!data.imageUrl) { throw new Error('Generation API response missing imageUrl.'); } console.log("[useImageGenerationDialog] Generation successful, imageUrl:", data.imageUrl); setGeneratedImageUrl(data.imageUrl); setGenerationSuccess(true); toast({ title: "Generation Complete!", description: "Image generated successfully.", className: "bg-green-500/10 text-green-700 dark:text-green-400 border-green-500/50" }); } catch (error) { const errorMessage = error instanceof Error ? error.message : "Unknown generation error."; console.error("[useImageGenerationDialog] Generation error:", errorMessage); setGenerationError(errorMessage); toast({ title: 'Generation Error', description: errorMessage, variant: 'destructive' }); } finally { setIsGeneratingImage(false); } }, [generationApiEndpoint]); return { generateImageDialogOpen, setGenerateImageDialogOpen, dialogStep, loadingPrompts, availablePrompts, dialogSelectedPrompt, isGeneratingImage, generationError, generationSuccess, generatedImageUrl, openDialog, handleDialogPromptSelect, handleGoToOptions, handleGoBackToPromptSelect, triggerImageGeneration, }; }