import { FieldType, type FieldInfo, type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { useFieldStore } from '@/ui/stores/fields'
import { DragDropProvider, KeyboardSensor, PointerSensor, type DragEndEvent } from '@dnd-kit/react'
import { useSortable } from '@dnd-kit/react/sortable'
import { useMutation } from '@tanstack/react-query'
import { InferRequestType, InferResponseType } from 'hono/client'
import { Button } from '@/ui/components/ui/button'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/ui/components/ui/dropdown-menu'
import { Input } from '@/ui/components/ui/input'
import { Label } from '@/ui/components/ui/label'
import { Switch } from '@/ui/components/ui/switch'
import { arrayMove } from '@/ui/lib/dnd-utils'
import { PointerActivationConstraints } from '@dnd-kit/dom'
import { ChevronDown, GripVertical, Plus, Search, Settings, Sparkles } from 'lucide-react'
import { useMemo, useState } from 'react'
type SortableFieldItemProps = {
field: FieldInfo
index: number
onVisibilityChange: (fieldId: string, visible: boolean) => void
}
function SortableFieldItem({ field, index, onVisibilityChange }: SortableFieldItemProps) {
const { ref, handleRef } = useSortable({
id: field.id!,
index,
})
return (
{field.aiAutofill &&
}
{field.config?.name}
onVisibilityChange(field.id!, checked)}
/>
)
}
type FieldsManagerProps = {
projectId: string
onManageFields?: () => void
onSave?: () => void
}
export function FieldsManager({ projectId, onManageFields, onSave }: FieldsManagerProps) {
const { fields, updateFields } = useFieldStore()
const [searchQuery, setSearchQuery] = useState('')
const [view, setView] = useState<'list' | 'create'>('list')
const [newFieldName, setNewFieldName] = useState('')
const [newFieldType, setNewFieldType] = useState('')
const [newAiAutofill, setNewAiAutofill] = useState(false)
const [newDescription, setNewDescription] = useState('')
const $patchOrder = client.api.projects[':projectId'].fields.order.$patch
const { mutate: updateFieldsOrder } = useMutation<
InferResponseType,
Error,
InferRequestType
>({
mutationFn: async (request) => {
const res = await $patchOrder(request)
if (!res.ok) throw new Error('Failed to update fields order')
return null as unknown as InferResponseType
},
})
const $post = client.api.projects[':projectId'].fields.$post
const { mutate: createField } = useMutation<
InferResponseType,
Error,
InferRequestType
>({
mutationFn: async (request) => {
const res = await $post(request)
if (!res.ok) throw new Error('Failed to create field')
return (await res.json()) as MetadataFieldInfo
},
onSuccess: (data) => {
const newField: MetadataFieldInfo = {
...(data as MetadataFieldInfo),
visible: true,
}
const newFieldsList = [...fields, newField]
updateFields(newFieldsList)
setNewFieldName('')
updateFieldsOrder({
param: { projectId: projectId },
json: newFieldsList.map((f) => ({
fieldId: f.id!,
visible: f.visible || false,
})),
})
onSave?.()
},
})
const filteredFields = useMemo(
() =>
fields.filter((field) =>
field.config?.name?.toLowerCase().includes(searchQuery.toLowerCase()),
),
[fields, searchQuery],
)
const handleDragEnd = (event: DragEndEvent) => {
const { source, target } = event.operation
if (source && target && source.id !== target.id) {
const oldIndex = fields.findIndex((f) => f.id === source.id)
const newIndex = fields.findIndex((f) => f.id === target.id)
const newFields = arrayMove(fields, oldIndex, newIndex)
updateFields(newFields)
updateFieldsOrder({
param: { projectId: projectId },
json: newFields.map((f: MetadataFieldInfo) => ({
fieldId: f.id!,
visible: f.visible || false,
})),
})
}
}
const handleVisibilityChange = (fieldId: string, visible: boolean) => {
const newFields = fields.map((f) => (f.id === fieldId ? { ...f, visible } : f))
updateFields(newFields)
updateFieldsOrder({
param: { projectId: projectId },
json: newFields.map((f) => ({
fieldId: f.id!,
visible: f.visible || false,
})),
})
}
const handleCreateField = () => {
if (!newFieldName || !newFieldType) return
createField({
param: { projectId: projectId },
json: {
config: {
name: newFieldName,
type: newFieldType,
},
label: newFieldName,
aiAutofill: newAiAutofill,
description: newDescription,
},
})
}
const visibleCount = fields.filter((f) => f.visible).length
if (view === 'create') {
return (
)
}
return (
Fields{' '}
({visibleCount} visible)
setSearchQuery(e.target.value)}
className="pl-8"
/>
{filteredFields.map((field, index) => (
))}
{onManageFields && (
)}
)
}