import { FormControl, useControl } from '@websolutespa/bom-mixer-forms';
import { useLabel } from '@websolutespa/bom-mixer-hooks';
import { ReactNode, useId } from 'react';
import { Field, InputProps, Label } from '../forms';
import { FieldError } from './field-error';

type FieldImplicitProps = InputProps & {
  control: FormControl;
  before?: ReactNode;
  after?: ReactNode;
};

export function FieldImplicit({ control, before, after, ...props }: FieldImplicitProps) {
  const uid = useId();
  const label = useLabel();

  const uniqueName = `${control.name}-${uid}`;

  const [state, setValue, setTouched] = useControl<string>(control);

  const controlLabel = control.label && label(control.label);
  return (
    state.flags.hidden ? (
      <input type="hidden" value={state.value || ''} />
    ) : (
      <Field state={state}>

        <Label htmlFor={uniqueName}>
          <input className="checkbox" type="hidden" id={uniqueName} name={uniqueName} value={String(state.value)} />
          {controlLabel && (
            <span dangerouslySetInnerHTML={{ __html: controlLabel }}></span>
          )}
        </Label>

        <FieldError state={state} />
      </Field>
    )
  );
}

