
import { FormControl, useControl } from '@websolutespa/bom-mixer-forms';
import { useLabel } from '@websolutespa/bom-mixer-hooks';
import { ChangeEvent, FocusEvent, useId, useState } from 'react';
import { Text } from '../components';
import { Field, Label, Radio } from '../forms';
import { FieldError } from './field-error';

type FieldAcceptProps = {
  control: FormControl;
};

export function FieldAccept({ control }: FieldAcceptProps) {
  const uid = useId();
  const label = useLabel();

  const uniqueName = `${control.name}-${uid}`;
  const uniqueNameTrue = `${uniqueName}-true`;
  const uniqueNameFalse = `${uniqueName}-false`;

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

  const onSelect = (value: boolean) => {
    // console.log('value', value);
    setValue(value);
  };

  const onChange = (event: ChangeEvent<HTMLInputElement>) => {
    onSelect(event.target.value === 'true');
  };

  const [focus, setFocus] = useState(false);

  const onBlur = (_: FocusEvent<HTMLInputElement>) => {
    setTouched();
    setFocus(false);
  };

  const onFocus = (_: FocusEvent<HTMLInputElement>) => {
    setFocus(true);
  };

  const controlLabel = control.label && label(control.label);
  return (
    state.flags.hidden ? (
      <input type="hidden" value={state.value ? 'true' : 'false'} />
    ) : (
      <Field state={state} padding="1em 0" borderBottom="1px solid var(--color-neutral-200)">

        <Radio.Group defaultValue={state.value ? 'true' : 'false'}
          onChange={onChange}
          onBlur={onBlur}
          onFocus={onFocus}
        >
          <Label name={uniqueNameTrue} width="auto">
            <Radio
              value="true"
              name={uniqueNameTrue}
              id={uniqueNameTrue}
              disabled={state.flags.disabled || state.flags.readonly}
              aria-invalid={state.flags.invalid}
              aria-describedby={`${uniqueName}-error`}
            />
            {label('form.accept.true')}
          </Label>
          <Label name={uniqueNameFalse} width="auto">
            <Radio
              value="false"
              name={uniqueNameFalse}
              id={uniqueNameFalse}
              disabled={state.flags.disabled || state.flags.readonly}
            />
            {label('form.accept.false')}
          </Label>
        </Radio.Group>

        {controlLabel &&
          <Text>
            {controlLabel}
          </Text>
        }

        <FieldError state={state} id={`${uniqueName}-error`} />
      </Field>
    )
  );
}
