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

type FieldTextAreaProps = {
  control: FormControl;
};

export function FieldTextArea({ control }: FieldTextAreaProps) {
  const uid = useId();
  const label = useLabel();

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

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

  const onChange = (event: ChangeEvent<HTMLTextAreaElement>) => {
    // console.log('FieldTextArea', event.target.value);
    setValue(event.target.value);
    // control.value = event.target.value;
  };

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

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

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

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

        <TextArea
          id={uniqueName}
          name={uniqueName}
          placeholder={label(control.placeholder || control.label || '')}
          value={state.value || ''}
          onChange={onChange}
          onBlur={onBlur}
          onFocus={onFocus}
          required={state.errors.some(x => x.key === 'required')}
          disabled={state.flags.disabled}
          readOnly={state.flags.readonly}
          aria-invalid={state.flags.invalid}
          aria-describedby={`${uniqueName}-error`}
          width="100%" />

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

