import { useState } from 'react' import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import { client } from '@/ui/api/client' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card' import { Button } from '@/ui/components/ui/button' import { Input } from '@/ui/components/ui/input' import { Badge } from '@/ui/components/ui/badge' import { ScrollArea } from '@/ui/components/ui/scroll-area' import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from '@/ui/components/ui/dialog' import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from '@/ui/components/ui/alert-dialog' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/ui/components/ui/select' import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from '@/ui/components/ui/table' import { Key, Plus, Trash2, AlertCircle, ImageIcon, VideoIcon, CheckCircle2, Loader2, } from 'lucide-react' import { toast } from 'sonner' import { m } from '@/ui/paraglide/messages.js' import type { MediaGenerationSettingsResponse, MediaProviderStatus, EnabledMediaModel, CuratedMediaModel, } from '@shumai/dtos' const PROVIDER_NAMES: Record = { openai: 'OpenAI', google: 'Google', 'google-vertex': 'Google Vertex AI', xai: 'xAI', fal: 'Fal', replicate: 'Replicate', 'black-forest-labs': 'Black Forest Labs', klingai: 'Kling AI', togetherai: 'Together AI', fireworks: 'Fireworks AI', deepinfra: 'DeepInfra', luma: 'Luma', 'amazon-bedrock': 'Amazon Bedrock', alibaba: 'Alibaba', bytedance: 'ByteDance', minimax: 'MiniMax', prodia: 'Prodia', azure: 'Azure OpenAI', } export function ImageVideoGenerationSettings({ teamId }: { teamId: string }) { const queryClient = useQueryClient() // API Key Dialog State const [keyDialogOpen, setKeyDialogOpen] = useState(false) const [editingProvider, setEditingProvider] = useState(null) const [apiKeyInput, setApiKeyInput] = useState('') // Add Model Dialog State const [addDialogOpen, setAddDialogOpen] = useState(false) const [addType, setAddType] = useState<'image' | 'video'>('image') const [addProvider, setAddProvider] = useState('') const [selectedModelId, setSelectedModelId] = useState('') const [customModelId, setCustomModelId] = useState('') const [modelDisplayName, setModelDisplayName] = useState('') // Delete Model Confirmation State const [modelToDelete, setModelToDelete] = useState(null) // Fetch Media Generation Settings const { data: settings, isLoading } = useQuery({ queryKey: ['teams', teamId, 'media-generation'], queryFn: async () => { const res = await client.api.teams[':teamId']['media-generation'].$get({ param: { teamId }, }) if (!res.ok) throw new Error('Failed to fetch media generation settings') return (await res.json()) as MediaGenerationSettingsResponse }, }) // Fetch Curated Models for Add Dialog const { data: curatedModels, isLoading: isLoadingCurated } = useQuery({ queryKey: ['teams', teamId, 'media-generation', 'curated', addType, addProvider], queryFn: async () => { if (!addProvider) return [] const res = await client.api.teams[':teamId']['media-generation']['models']['curated'].$get({ param: { teamId }, query: { provider: addProvider, type: addType }, }) if (!res.ok) return [] return (await res.json()) as CuratedMediaModel[] }, enabled: addDialogOpen && !!addProvider, }) // Mutation: Update Provider API Key const { mutate: updateApiKey, isPending: isSavingKey } = useMutation({ mutationFn: async ({ provider, apiKey }: { provider: string; apiKey?: string }) => { const res = await client.api.teams[':teamId']['media-generation']['providers'][ ':provider' ].$put({ param: { teamId, provider }, json: { apiKey }, }) if (!res.ok) { const err = await res.json().catch(() => ({})) // eslint-disable-next-line @typescript-eslint/no-explicit-any throw new Error((err as any)?.message || 'Failed to update API key') } return await res.json() }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'media-generation'] }) toast.success(m.api_key_saved_successfully()) setKeyDialogOpen(false) setEditingProvider(null) setApiKeyInput('') }, onError: (err) => { toast.error(err instanceof Error ? err.message : m.failed_to_save_api_key()) }, }) // Mutation: Add Enabled Model const { mutate: addModel, isPending: isAddingModel } = useMutation({ mutationFn: async (payload: { type: 'image' | 'video' provider: string modelId: string name?: string }) => { const res = await client.api.teams[':teamId']['media-generation']['models'].$post({ param: { teamId }, json: payload, }) if (!res.ok) { const err = await res.json().catch(() => ({})) // eslint-disable-next-line @typescript-eslint/no-explicit-any throw new Error((err as any)?.message || 'Failed to add model') } return await res.json() }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'media-generation'] }) toast.success(m.model_added_successfully()) setAddDialogOpen(false) resetAddForm() }, onError: (err) => { toast.error(err instanceof Error ? err.message : m.failed_to_add_model()) }, }) // Mutation: Remove Enabled Model const { mutate: removeModel, isPending: isRemovingModel } = useMutation({ mutationFn: async (modelId: string) => { const res = await client.api.teams[':teamId']['media-generation']['models'][ ':modelId' ].$delete({ param: { teamId, modelId }, }) if (!res.ok) throw new Error('Failed to remove model') return await res.json() }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'media-generation'] }) toast.success(m.model_removed_successfully()) setModelToDelete(null) }, onError: (err) => { toast.error(err instanceof Error ? err.message : m.failed_to_remove_model()) }, }) const resetAddForm = () => { setAddType('image') setAddProvider('') setSelectedModelId('') setCustomModelId('') setModelDisplayName('') } const handleOpenKeyDialog = (provider: MediaProviderStatus) => { setEditingProvider(provider) setApiKeyInput('') setKeyDialogOpen(true) } const handleSaveKey = () => { if (!editingProvider) return const trimmed = apiKeyInput.trim() if (!trimmed) { setKeyDialogOpen(false) return } updateApiKey({ provider: editingProvider.provider, apiKey: trimmed, }) } const handleRemoveKey = () => { if (!editingProvider) return updateApiKey({ provider: editingProvider.provider, apiKey: '', }) } const handleAddModelSubmit = () => { const finalModelId = selectedModelId === '__custom__' ? customModelId.trim() : selectedModelId.trim() if (!addProvider || !finalModelId) return addModel({ type: addType, provider: addProvider, modelId: finalModelId, name: modelDisplayName.trim() || undefined, }) } if (isLoading) { return (
) } const providers = settings?.providers || [] const enabledModels = settings?.enabledModels || [] const activeProvidersMap = new Map(providers.map((p) => [p.provider, p.apiKeyConfigured])) // Filter providers that support the currently selected addType const compatibleProviders = providers.filter((p) => p.supportedTypes.includes(addType)) return (
{/* Section 1: Media Providers */} {m.media_providers()} {m.media_providers_description()}
{providers.map((provider) => { const displayName = PROVIDER_NAMES[provider.provider] || provider.provider const isCustom = provider.status === 'configured_custom' const isEnv = provider.status === 'configured_env' return (
{displayName} {isCustom && ( {m.provider_status_configured_custom()} )} {isEnv && ( {m.provider_status_configured_env()} )} {!isCustom && !isEnv && ( {m.provider_status_not_configured()} )}
{provider.supportedTypes.includes('image') && ( {m.media_type_image()} )} {provider.supportedTypes.includes('video') && ( {m.media_type_video()} )}
{provider.defaultEnvKey}
) })}
{/* Section 2: Enabled Models */}
{m.enabled_media_models()} {m.enabled_media_models_description()}
{enabledModels.length === 0 ? (

{m.no_enabled_models()}

) : (
{m.model_type()} {m.providers()} {m.model()} {enabledModels.map((model) => { const isConfigured = activeProvidersMap.get(model.provider) ?? false const providerDisplayName = PROVIDER_NAMES[model.provider] || model.provider return ( {model.type === 'image' ? ( {m.media_type_image()} ) : ( {m.media_type_video()} )} {providerDisplayName}
{model.modelId} {model.name && ( ({model.name}) )} {!isConfigured && (
{m.provider_status_not_configured()}
)}
) })}
)}
{/* Dialog: Configure Provider API Key */} {editingProvider ? `${PROVIDER_NAMES[editingProvider.provider] || editingProvider.provider} API Key` : m.configure_api_key()} {editingProvider && m.api_key_or_env_var_hint({ envKey: editingProvider.defaultEnvKey })}
setApiKeyInput(e.target.value)} placeholder={ editingProvider?.status === 'configured_custom' ? '••••••••' : editingProvider ? m.api_key_or_env_var_placeholder({ envKey: editingProvider.defaultEnvKey, }) : '' } className="font-mono text-sm" />
{editingProvider?.status === 'configured_custom' ? ( ) : (
)}
{/* Dialog: Add Model */} {m.add_media_model()} {m.add_media_model_desc()}
{/* Type Select */}
{/* Provider Select */}
{/* Model Select */} {addProvider && (
{isLoadingCurated ? (
{m.loading_models()}
) : ( )}
)} {/* Custom Model ID Input */} {selectedModelId === '__custom__' && (
setCustomModelId(e.target.value)} placeholder={m.enter_custom_model_id()} className="font-mono text-sm" />
)} {/* Display Name Input */} {addProvider && selectedModelId && (
setModelDisplayName(e.target.value)} placeholder={m.model_display_name_placeholder()} />
)}
{/* Alert Dialog: Confirm Model Deletion */} { if (!open) setModelToDelete(null) }} > {m.remove_model_confirm()} {modelToDelete && m.remove_model_prompt({ modelId: modelToDelete.modelId, provider: PROVIDER_NAMES[modelToDelete.provider] || modelToDelete.provider, })} {m.cancel()} { if (modelToDelete) removeModel(modelToDelete.id) }} disabled={isRemovingModel} className="bg-destructive text-destructive-foreground hover:bg-destructive/90" > {isRemovingModel && } {m.delete()}
) }