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

type FieldRadioProps = {
  control: FormControl;
};

export function FieldRadio({ control, ...props }: FieldRadioProps & FieldProps) {
  const uid = useId();
  const label = useLabel();

  const id = useId();
  // const uniqueName = `${control.name}-${uid}`;
  const uniqueName = id;

  const getUniqueName = (option: IOption) => {
    return `${uniqueName}-${option.id}`;
  };

  const [state, setValue, setTouched] = useControl<IOption | null>(control);

  const onChange = (event: ChangeEvent<HTMLInputElement>) => {
    // console.log('onChange', event.target.checked);
    const option = control.options?.find(x => String(x.id) === event.target.value);
    setValue(option || null);
  };

  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={valueToString(state.value)} />
    ) : (
      <Field state={state} {...props}>

        <Radio.Group
          defaultValue={state.value ? 'true' : 'false'}
          onChange={onChange}
          onBlur={onBlur}
          onFocus={onFocus}
        >
          {controlLabel && (
            <Radio.GroupLabel>{controlLabel}</Radio.GroupLabel>
          )}
          {control.options?.map((option) => (
            <Label key={getUniqueName(option)} htmlFor={getUniqueName(option)}>
              <Radio
                id={getUniqueName(option)}
                name={uniqueName}
                value={String(option.id)}
                disabled={state.flags.disabled || state.flags.readonly}
                checked={state.value?.id === option.id}
              /> {option.name}
            </Label>
          ))}
        </Radio.Group>

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