import { useQuery } from '@tanstack/react-query'
import { Link } from '@tanstack/react-router'
import { useParams } from 'common'
import { map as lodashMap, uniqBy } from 'lodash'
import { HelpCircleIcon, TerminalIcon } from 'lucide-react'
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger, Button, SidePanel } from 'ui'
import { EmptyStatePresentational } from 'ui-patterns/EmptyStatePresentational'
import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'
import InformationBox from '@/components/ui/InformationBox'
import {
databaseFunctionsQueryOptions,
type DatabaseFunction,
} from '@/data/database-functions/database-functions-query'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { useGrant } from '@/lib/grants'
export interface ChooseFunctionFormProps {
visible: boolean
setVisible: (value: boolean) => void
onChange: (fn: DatabaseFunction) => void
}
export const ChooseFunctionForm = ({ visible, onChange, setVisible }: ChooseFunctionFormProps) => {
const { data: project } = useSelectedProjectQuery()
const readGrant = useGrant(
'POST /platform/pg-meta/{ref}/query',
{ projectRef: project?.ref },
{ variant: 'read' }
)
const { data = [] } = useQuery(
databaseFunctionsQueryOptions({
projectRef: project?.ref,
connectionString: project?.connectionString,
grant: readGrant.grant,
})
)
const triggerFunctions = data.filter((fn) => fn.return_type === 'trigger')
const hasPublicSchemaFunctions = triggerFunctions.length >= 1
const functionSchemas = lodashMap(uniqBy(triggerFunctions, 'schema'), 'schema')
const selectFunction = (id: number) => {
const fn = triggerFunctions.find((x) => x.id === id)
if (!!fn) onChange(fn)
setVisible(!visible)
}
return (
{name}