import type { StatusDotStatus } from '@langgenius/dify-ui/status-dot'
import type { Credential, PluginPayload } from './types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { StatusDot } from '@langgenius/dify-ui/status-dot'
import { RiArrowDownSLine } from '@remixicon/react'
import { memo, useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Authorized, usePluginAuth } from '.'
type AuthorizedInNodeProps = {
pluginPayload: PluginPayload
onAuthorizationItemClick: (id: string) => void
credentialId?: string
onDefaultCredentialChange?: (id?: string) => void
}
const AuthorizedInNode = ({
pluginPayload,
onAuthorizationItemClick,
credentialId,
onDefaultCredentialChange,
}: AuthorizedInNodeProps) => {
const { t } = useTranslation()
const [isOpen, setIsOpen] = useState(false)
const {
canApiKey,
canOAuth,
credentials,
isLoading,
invalidPluginCredentialInfo,
notAllowCustomCredential,
} = usePluginAuth(pluginPayload, true, credentialId ? [credentialId] : undefined)
const defaultCredentialId = credentials.find((c) => c.is_default)?.id
useEffect(() => {
onDefaultCredentialChange?.(defaultCredentialId)
}, [defaultCredentialId, onDefaultCredentialChange])
const renderTrigger = useCallback(
(open?: boolean) => {
let label = ''
let removed = false
let unavailable = false
let color: StatusDotStatus = 'success'
let defaultUnavailable = false
if (!credentialId) {
label = t(($) => $['auth.workspaceDefault'], { ns: 'plugin' })
const defaultCredential = credentials.find((c) => c.is_default)
if (defaultCredential?.not_allowed_to_use) {
color = 'disabled'
defaultUnavailable = true
}
} else {
const credential = credentials.find((c) => c.id === credentialId)
if (credential) label = credential.name
else if (isLoading) {
label = t(($) => $.loading, { ns: 'common' })
color = 'disabled'
} else {
label = t(($) => $['auth.authRemoved'], { ns: 'plugin' })
removed = true
}
unavailable = !!credential?.not_allowed_to_use && !credential?.from_enterprise
if (removed) color = 'error'
else if (unavailable) color = 'disabled'
}
return (
)
},
[credentialId, credentials, isLoading, t],
)
const defaultUnavailable = credentials.find((c) => c.is_default)?.not_allowed_to_use
const extraAuthorizationItems: Credential[] = [
{
id: '__workspace_default__',
name: t(($) => $['auth.workspaceDefault'], { ns: 'plugin' }),
provider: '',
is_default: !credentialId,
isWorkspaceDefault: true,
not_allowed_to_use: defaultUnavailable,
},
]
const handleAuthorizationItemClick = useCallback(
(id: string) => {
onAuthorizationItemClick(
id === '__workspace_default__' && onDefaultCredentialChange
? defaultCredentialId || id
: id,
)
setIsOpen(false)
},
[defaultCredentialId, onDefaultCredentialChange, onAuthorizationItemClick, setIsOpen],
)
return (
)
}
export default memo(AuthorizedInNode)