/**
 * This Source Code is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Copyright (c) Infonomic Company Limited
 */
import { ErrorText, Label, Select } from '@byline/ui/react';
import cx from 'clsx';
import { useFieldError, useFieldValue, useIsDirty } from '../../forms/form-context';
import styles from './select-field.module.css';
export const SelectField = ({ field, value, defaultValue, onChange, id, path, }) => {
    const fieldPath = path ?? field.name;
    const fieldError = useFieldError(fieldPath);
    const isDirty = useIsDirty(fieldPath);
    const fieldValue = useFieldValue(fieldPath);
    const incomingValue = value ?? fieldValue ?? defaultValue ?? '';
    const htmlId = id ?? fieldPath;
    return (<div className={`byline-field-select ${field.name}`}>
      {field.label && (<Label id={htmlId} htmlFor={htmlId} label={field.label} required={!field.optional} className={cx('byline-field-select-label', styles.label)}/>)}
      <Select size="xs" variant="outlined" id={htmlId} name={field.name} placeholder="Select an option" required={!field.optional} value={incomingValue} ariaLabel={field.label} helpText={field.helpText} items={field.options.map((opt) => ({ value: opt.value, label: opt.label }))} onValueChange={(value) => {
            if (value != null)
                onChange?.(value);
        }} className={cx(isDirty && ['byline-field-select-dirty', styles.dirty])}/>
      {fieldError && <ErrorText id={`${field.name}-error`} text={fieldError}/>}
    </div>);
};
