import { useEffect, useMemo, useState } from "react"; import { Check, Database, FileText, Loader2, RefreshCw } from "lucide-react"; import { getDatabaseClients, getDocuments, type DataBindItem, } from "@/services/orchestrationApi"; import { getCurrentSession } from "./session"; import { cx, uniqueById } from "./utils"; interface DataBindSelectorProps { value: DataBindItem[]; onChange: (items: DataBindItem[]) => void; disabled?: boolean; } export function DataBindSelector({ value, onChange, disabled }: DataBindSelectorProps) { const [options, setOptions] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const selected = useMemo(() => new Set(value.map((item) => item.id)), [value]); const loadOptions = async () => { const session = getCurrentSession(); if (!session?.user_id) return; setLoading(true); setError(null); try { const [docs, dbs] = await Promise.all([getDocuments(session.user_id), getDatabaseClients(session.user_id)]); const docItems = docs .filter((doc) => ["processed", "completed", "uploaded", "processing"].includes(doc.status)) .map((doc) => ({ id: doc.id, name: doc.filename, group_type: "document", type: doc.file_type, })); const dbItems = dbs .filter((db) => db.status !== "inactive") .map((db) => ({ id: db.id, name: db.name, group_type: "database", type: db.db_type, })); setOptions(uniqueById([...docItems, ...dbItems])); } catch (err) { setError(err instanceof Error ? err.message : "Failed to load sources"); } finally { setLoading(false); } }; useEffect(() => { loadOptions(); }, []); const toggle = (item: DataBindItem) => { if (disabled) return; if (selected.has(item.id)) { onChange(value.filter((existing) => existing.id !== item.id)); return; } onChange([...value, item]); }; return (
{error &&

{error}

}
{loading ? (
Loading sources
) : options.length === 0 ? (
No eligible sources yet.
) : ( options.map((item) => { const isSelected = selected.has(item.id); const Icon = item.group_type === "database" ? Database : FileText; return ( ); }) )}
{value.length === 0 &&

Select at least one source.

}
); }