import { useState, useMemo } 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 { Tabs, TabsContent, TabsList, TabsTrigger } from '@/ui/components/ui/tabs' 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 { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from '@/ui/components/ui/table' import { Key, Plus, Trash2, AlertCircle, ImageIcon, VideoIcon, CheckCircle2, Loader2, Check, } 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() // Tab State const [activeTab, setActiveTab] = useState<'providers' | 'models'>('providers') // 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('') // 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('') } const handleOpenKeyDialog = (provider: MediaProviderStatus) => { setEditingProvider(provider) setApiKeyInput(provider.customApiKeyOrEnv || '') setKeyDialogOpen(true) } const handleSaveKey = () => { if (!editingProvider) return const trimmed = apiKeyInput.trim() updateApiKey({ provider: editingProvider.provider, apiKey: trimmed, }) } const handleRemoveKey = () => { if (!editingProvider) return updateApiKey({ provider: editingProvider.provider, apiKey: '', }) } const handleTypeChange = (type: 'image' | 'video') => { if (type === addType) return setAddType(type) // Check if current provider supports the new type const providerObj = settings?.providers?.find((p) => p.provider === addProvider) if (!providerObj || !providerObj.supportedTypes.includes(type)) { setAddProvider('') setSelectedModelId('') setCustomModelId('') } else { setSelectedModelId('') setCustomModelId('') } } const handleAddModelSubmit = () => { const finalModelId = selectedModelId === '__custom__' ? customModelId.trim() : selectedModelId.trim() if (!addProvider || !finalModelId) return const curated = curatedModels?.find((m) => m.modelId === finalModelId) const finalName = curated?.name || finalModelId addModel({ type: addType, provider: addProvider, modelId: finalModelId, name: finalName, }) } 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 = useMemo( () => providers.filter((p) => p.supportedTypes.includes(addType)), [providers, addType], ) if (isLoading) { return (
) } return (
setActiveTab(val as 'providers' | 'models')} className="w-full flex-1 flex flex-col min-h-0 min-w-0" > setActiveTab('providers')}> {m.providers()} setActiveTab('models')}> {m.enabled_media_models()} {/* Tab 1: Providers */}
{m.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.customApiKeyOrEnv || provider.defaultEnvKey}
) })}
{/* Tab 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.default_env_var_desc({ envKey: editingProvider.defaultEnvKey })}
setApiKeyInput(e.target.value)} placeholder={m.api_key_placeholder()} className="font-mono text-sm" />

{m.api_key_description()}

{editingProvider?.status === 'configured_custom' ? ( ) : (
)}
{/* Dialog: Add Model */} {m.add_media_model()} {m.add_media_model_desc()}
{/* 1. Model Type Selector: 2-Card Switch */}
{/* Image Card */} {/* Video Card */}
{/* 2. Provider / Model Selector: 2 Boxes Side-by-Side */}
{/* Left Box: Providers */}
{m.providers()} {compatibleProviders.length}
{compatibleProviders.map((p) => { const isSelected = addProvider === p.provider const displayName = PROVIDER_NAMES[p.provider] || p.provider return ( ) })}
{/* Right Box: Models */}
{m.models()} {addProvider && ( {PROVIDER_NAMES[addProvider] || addProvider} )}
{!addProvider ? (

{m.select_provider_first()}

) : isLoadingCurated ? (
{m.loading_models()}
) : (
{(curatedModels || []).map((curated) => { const isSelected = selectedModelId === curated.modelId return ( ) })} {/* Custom Model Option */}
)}
{/* 3. Inputs below 2 boxes */} {selectedModelId === '__custom__' && (
setCustomModelId(e.target.value)} placeholder={m.enter_custom_model_id()} className="font-mono text-sm" />
)}
{/* 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()}
) }