import { IEquatable, IOption } from '@websolutespa/bom-core';
import { FormControl, useControl, valueToString } from '@websolutespa/bom-mixer-forms';
import { useLabel } from '@websolutespa/bom-mixer-hooks';
import { IconChevronDown } from '@websolutespa/bom-mixer-icons';
import { FocusEvent, ReactElement, useId } from 'react';
import { Combobox, Field, filterOptions } from '../forms';
import { FieldError } from './field-error';

type FieldComboboxProps = {
  control: FormControl;
  icon?: ReactElement;
};

export function FieldCombobox({ control, icon }: FieldComboboxProps) {
  const uid = useId();
  const label = useLabel();

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

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

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

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

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

  const onChange = (option: string | IOption | string[] | IOption[] | null) => {
    setValue(option);
  };

  // console.log('FieldCombobox', control.value);

  const controlLabel = control.label && label(control.label);
  return (
    state.flags.hidden ? (
      <input type="hidden" value={valueToString(state.value)} />
    ) : (
      <Field state={state}>
        <Combobox
          name={uniqueName}
          selectedValue={control.value}
          options={control.options}
          onChange={onChange}
          onFocus={onFocus}
          onBlur={onBlur}
        >
          {controlLabel && (
            <Combobox.Label>{controlLabel}</Combobox.Label>
          )}
          <Combobox.Combobox
            after={icon || <IconChevronDown />}
            autoSelect
            placeholder={control.placeholder && label(control.placeholder)}
            aria-invalid={state.flags.invalid}
            aria-describedby={`${uniqueName}-error`}
          >
          </Combobox.Combobox>
          <Combobox.Popover gutter={4} sameWidth data-lenis-prevent
            renderOptions={(value?: string) => {
              if (!control.options) {
                return;
              }
              const filteredOptions = filterOptions(control.options, value);
              return filteredOptions.length ? (
                filteredOptions.map((option) => (
                  <Combobox.Option key={option.id} value={option.name}>
                    <Combobox.OptionValue />
                  </Combobox.Option>
                ))
              ) : (
                <Combobox.Empty>{label('noResults')}</Combobox.Empty>
              );
            }} />
        </Combobox>
        {control.customData?.after && (
          control.customData.after
        )}
        <FieldError state={state} label={controlLabel} id={`${uniqueName}-error`} />
      </Field>
    )
  );
}
