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

type FieldCheckboxProps = {
  control: FormControl;
};

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

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

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

  const onChange = (event: ChangeEvent<HTMLInputElement>) => {
    // console.log('onChange', event.target.checked);
    setValue(event.target.checked);
  };

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

        {/* type={(state.flags.invalid && state.flags.touched) ? 'error' : 'default'} */}

        <Label htmlFor={uniqueName} margin="0">
          <Checkbox
            id={uniqueName}
            name={uniqueName}
            onChange={onChange}
            onBlur={onBlur}
            onFocus={onFocus}
            disabled={state.flags.disabled || state.flags.readonly}
            checked={state.value === true}
            aria-invalid={state.flags.invalid}
            aria-describedby={`${uniqueName}-error`}
          />
          {controlLabel && (
            <span dangerouslySetInnerHTML={{ __html: controlLabel }}></span>
          )}
        </Label>

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

// {JSON.stringify(props.control.errors[key])}
