import { useState, useMemo, useEffect } 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 { Switch } from '@/ui/components/ui/switch' import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/ui/components/ui/tabs' import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from '@/ui/components/ui/dialog' import { Plus, Trash2, AlertCircle, ImageIcon, VideoIcon, CheckCircle2, Loader2, Search, ChevronRight, } from 'lucide-react' import { toast } from 'sonner' import { m } from '@/ui/paraglide/messages.js' import { cn } from '@/ui/lib/utils' import type { MediaGenerationSettingsResponse, MediaProviderStatus, EnabledMediaModel, CuratedMediaModel, MediaModelType, } 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', } interface StagedModelItem { type: MediaModelType modelId: string name?: string isCustom?: boolean } export function ImageVideoGenerationSettings({ teamId }: { teamId: string }) { const queryClient = useQueryClient() const [selectedProvider, setSelectedProvider] = 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 }, }) const providers = settings?.providers || [] const enabledModels = settings?.enabledModels || [] // Keep selectedProvider up to date when settings refetch const currentSelectedProvider = useMemo(() => { if (!selectedProvider) return null return providers.find((p) => p.provider === selectedProvider.provider) || selectedProvider }, [selectedProvider, providers]) if (isLoading) { return (
) } return (
{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' const imageCount = enabledModels.filter( (m) => m.provider === provider.provider && m.type === 'image', ).length const videoCount = enabledModels.filter( (m) => m.provider === provider.provider && m.type === 'video', ).length return (
setSelectedProvider(provider)} className="group cursor-pointer flex items-center justify-between gap-4 p-3.5 rounded-xl border border-border bg-card/50 hover:bg-card/80 hover:border-primary/50 transition-all shadow-none hover:shadow-xs min-w-0" >
{/* Row 1: Provider Name + Env / Custom Key */}
{displayName} {provider.customApiKeyOrEnv || provider.defaultEnvKey}
{/* Row 2: All labels (configured status, n image enabled, n video enabled) */}
{isCustom && ( {m.provider_status_configured_custom()} )} {isEnv && ( {m.provider_status_configured_env()} )} {!isCustom && !isEnv && ( {m.provider_status_not_configured()} )} {provider.supportedTypes.includes('image') && ( 0 ? 'bg-primary/10 text-primary border-primary/20' : 'bg-muted/50 text-muted-foreground border-border/60', )} > {m.image_models_count({ count: imageCount })} )} {provider.supportedTypes.includes('video') && ( 0 ? 'bg-purple-500/10 text-purple-600 dark:text-purple-400 border-purple-500/20' : 'bg-muted/50 text-muted-foreground border-border/60', )} > {m.video_models_count({ count: videoCount })} )}
) })}
{/* Provider Details Dialog */} {currentSelectedProvider && ( setSelectedProvider(null)} provider={currentSelectedProvider} teamId={teamId} enabledModels={enabledModels} onSuccess={() => { queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'media-generation'] }) }} /> )}
) } interface ProviderDetailsDialogProps { isOpen: boolean onClose: () => void provider: MediaProviderStatus teamId: string enabledModels: EnabledMediaModel[] onSuccess: () => void } function ProviderDetailsDialog({ isOpen, onClose, provider, teamId, enabledModels, onSuccess, }: ProviderDetailsDialogProps) { // Smart default: open to 'models' if key is configured, else 'api-key' const [activeTab, setActiveTab] = useState<'api-key' | 'models'>(() => provider.apiKeyConfigured ? 'models' : 'api-key', ) // Staged API Key state const [stagedApiKey, setStagedApiKey] = useState(provider.customApiKeyOrEnv || '') // Staged Models state const [stagedModels, setStagedModels] = useState(() => enabledModels .filter((m) => m.provider === provider.provider) .map((m) => ({ type: m.type, modelId: m.modelId, name: m.name, })), ) // Filter & Search states const [searchQuery, setSearchQuery] = useState('') const [modalityFilter, setModalityFilter] = useState<'all' | 'image' | 'video'>('all') // Custom Model Form state const [customModelId, setCustomModelId] = useState('') const [customType, setCustomType] = useState( provider.supportedTypes[0] || 'image', ) // Reset states if provider or dialog open status changes useEffect(() => { setActiveTab(provider.apiKeyConfigured ? 'models' : 'api-key') setStagedApiKey(provider.customApiKeyOrEnv || '') setStagedModels( enabledModels .filter((m) => m.provider === provider.provider) .map((m) => ({ type: m.type, modelId: m.modelId, name: m.name, })), ) setSearchQuery('') setModalityFilter('all') setCustomModelId('') setCustomType(provider.supportedTypes[0] || 'image') }, [provider.provider, provider.customApiKeyOrEnv, provider.apiKeyConfigured, enabledModels]) // Fetch Curated Models for this Provider const { data: curatedModels = [], isLoading: isLoadingCurated } = useQuery({ queryKey: ['teams', teamId, 'media-generation', 'curated', provider.provider], queryFn: async () => { const res = await client.api.teams[':teamId']['media-generation']['models']['curated'].$get({ param: { teamId }, query: { provider: provider.provider }, }) if (!res.ok) return [] return (await res.json()) as CuratedMediaModel[] }, enabled: isOpen, }) // Mutation: Save provider configuration (API Key + Models) const { mutate: saveProviderConfig, isPending: isSaving } = useMutation({ mutationFn: async () => { const res = await client.api.teams[':teamId']['media-generation']['providers'][ ':provider' ].$put({ param: { teamId, provider: provider.provider }, json: { apiKey: stagedApiKey.trim(), models: stagedModels.map((m) => ({ type: m.type, modelId: m.modelId, name: m.name || m.modelId, })), }, }) 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 provider') } return await res.json() }, onSuccess: () => { toast.success(m.provider_updated_successfully()) onSuccess() onClose() }, onError: (err) => { toast.error(err instanceof Error ? err.message : m.failed_to_update_provider()) }, }) // Determine curated vs custom models const curatedModelIds = useMemo( () => new Set(curatedModels.map((m) => m.modelId)), [curatedModels], ) const customModels = useMemo( () => stagedModels.filter((m) => !curatedModelIds.has(m.modelId)), [stagedModels, curatedModelIds], ) // Combine curated models and custom models for rendering const allDisplayModels = useMemo(() => { const list: Array<{ type: MediaModelType modelId: string name: string isCustom: boolean isToggledOn: boolean }> = [] // 1. Add curated models (default disabled unless in stagedModels) for (const curated of curatedModels) { const isToggledOn = stagedModels.some( (m) => m.modelId === curated.modelId && m.type === curated.type, ) list.push({ type: curated.type, modelId: curated.modelId, name: curated.name, isCustom: false, isToggledOn, }) } // 2. Add custom models (always toggled on while in stagedModels) for (const custom of customModels) { list.push({ type: custom.type, modelId: custom.modelId, name: custom.name || custom.modelId, isCustom: true, isToggledOn: true, }) } return list }, [curatedModels, stagedModels, customModels]) // Filter models by search query and modality filter const filteredModels = useMemo(() => { return allDisplayModels.filter((model) => { if (modalityFilter !== 'all' && model.type !== modalityFilter) { return false } if (searchQuery.trim()) { const q = searchQuery.toLowerCase() const matchName = model.name.toLowerCase().includes(q) const matchId = model.modelId.toLowerCase().includes(q) if (!matchName && !matchId) return false } return true }) }, [allDisplayModels, modalityFilter, searchQuery]) // Toggle model handler const handleToggleModel = ( model: { type: MediaModelType; modelId: string; name: string; isCustom: boolean }, checked: boolean, ) => { if (checked) { // Enable model setStagedModels((prev) => [ ...prev, { type: model.type, modelId: model.modelId, name: model.name, isCustom: model.isCustom, }, ]) } else { // Disable model (for curated, turns off; for custom, removes from stagedModels) setStagedModels((prev) => prev.filter((m) => !(m.modelId === model.modelId && m.type === model.type)), ) } } // Remove custom model const handleRemoveCustomModel = (modelId: string, type: MediaModelType) => { setStagedModels((prev) => prev.filter((m) => !(m.modelId === modelId && m.type === type))) } // Add custom model handler const handleAddCustomModel = () => { const trimmed = customModelId.trim() if (!trimmed) return // Check duplicate const alreadyStaged = stagedModels.some((m) => m.modelId === trimmed && m.type === customType) if (alreadyStaged) { toast.error(m.failed_to_add_model()) return } setStagedModels((prev) => [ ...prev, { type: customType, modelId: trimmed, name: trimmed, isCustom: true, }, ]) setCustomModelId('') } const displayName = PROVIDER_NAMES[provider.provider] || provider.provider return ( !open && onClose()}> {displayName} {provider.status === 'configured_custom' && ( {m.provider_status_configured_custom()} )} {provider.status === 'configured_env' && ( {m.provider_status_configured_env()} )} {m.default_env_var_desc({ envKey: provider.defaultEnvKey })} setActiveTab(val as 'api-key' | 'models')} className="flex-1 flex flex-col min-h-0" >
setActiveTab('api-key')}> {m.api_key()} setActiveTab('models')}> {m.models()} ({stagedModels.length})
{/* Tab 1: API Key Config */}
{stagedApiKey && ( )}
setStagedApiKey(e.target.value)} placeholder={m.api_key_or_env_var_placeholder({ envKey: provider.defaultEnvKey, })} className="font-mono text-sm" />

{m.api_key_or_env_var_hint({ envKey: provider.defaultEnvKey })}

{/* Tab 2: Models List */} {/* Unconfigured Warning Notice */} {!provider.apiKeyConfigured && !stagedApiKey && (

{m.provider_status_not_configured()}

{m.provider_not_configured_warning()}

)} {/* Filter Bar: Search + Modality Filter */}
setSearchQuery(e.target.value)} className="pl-9 h-9 text-xs" />
{provider.supportedTypes.length > 1 && (
)}
{/* Models List */}
{isLoadingCurated ? (
{m.loading_models()}
) : filteredModels.length === 0 ? (
{m.no_models_found()}
) : (
{filteredModels.map((model) => (
{model.type === 'image' ? ( ) : ( )} {model.type === 'image' ? m.media_type_image() : m.media_type_video()}
{model.name} {model.isCustom && ( {m.custom_model_option().replace('...', '')} )}

{model.modelId}

{model.isCustom && ( )} handleToggleModel(model, checked)} aria-label={`Toggle ${model.name}`} />
))}
)}
{/* Minimal Add Custom Model Form */}
{provider.supportedTypes.length > 1 && (
)} setCustomModelId(e.target.value)} placeholder={m.enter_custom_model_id()} className="font-mono text-xs h-8 flex-1" onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault() handleAddCustomModel() } }} />
{/* Global Footer with Cancel and Save */}
{stagedModels.length} {m.models().toLowerCase()}
) }