import { useState, useMemo } from 'react';
import { useNomenclatureData } from '../../contexts/NomenclatureDataContext';
import NomenclatureManagementOverlay from './NomenclatureManagementOverlay';
import './NomenclatureDropdown.css';
export default function NomenclatureDropdown({
nomenclatureCode,
value,
onChange,
label,
disabled = false,
}) {
const { definitions, getActiveEntries, isLoading } = useNomenclatureData();
const [showOverlay, setShowOverlay] = useState(false);
const nomenclature = definitions[nomenclatureCode];
const activeEntries = useMemo(
() => getActiveEntries(nomenclatureCode),
[getActiveEntries, nomenclatureCode]
);
if (!nomenclature) {
if (isLoading) {
return (
{label && {label} }
Loading...
);
}
return null;
}
const displayLabel = label || nomenclature.name;
// SELECTOR type: choices come from selector_options, value is the option string.
// No manage button - options are configured in the admin screen, not while weighing.
if (nomenclature.kind === 'selector') {
const options = nomenclature.selector_options || [];
const isUnknown = value && !options.some(o => o.value === value);
return (
{displayLabel}
onChange(e.target.value || undefined)}
disabled={disabled}
>
-- Select --
{options.map(opt => (
{opt.label}
))}
{isUnknown && (
{value} (unknown)
)}
);
}
// LOOKUP type: select dropdown + manage button
if (nomenclature.kind === 'lookup') {
const handleSelectChange = (e) => {
const val = e.target.value;
onChange(val ? parseInt(val, 10) : undefined);
};
const handleOverlaySelect = (entryId) => {
onChange(entryId);
setShowOverlay(false);
};
return (
{displayLabel}
-- Select --
{activeEntries.map(entry => (
{entry.display_value}
))}
setShowOverlay(true)}
disabled={disabled}
type="button"
title={`Manage ${displayLabel}`}
>
…
setShowOverlay(false)}
mode="select"
initialSelection={value || null}
onSelect={handleOverlaySelect}
/>
);
}
// FIELD type: render appropriate input
const fieldDef = nomenclature.fields?.[0];
if (!fieldDef) return null;
if (fieldDef.field_type === 'bool') {
return (
onChange(e.target.checked)}
disabled={disabled}
className="nui-dropdown-checkbox"
/>
{displayLabel}
);
}
if (fieldDef.field_type === 'number') {
return (
{displayLabel}
onChange(e.target.value === '' ? undefined : Number(e.target.value))}
disabled={disabled}
/>
);
}
if (fieldDef.field_type === 'choice' && fieldDef.choices) {
return (
{displayLabel}
onChange(e.target.value || undefined)}
disabled={disabled}
>
-- Select --
{fieldDef.choices.map(c => (
{c}
))}
);
}
// Default: text input
return (
{displayLabel}
onChange(e.target.value || undefined)}
disabled={disabled}
/>
);
}