import { getClassNames, 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 { Field, Select } from '../forms';
import { FieldError } from './field-error';

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

export function FieldSelect({ control, icon }: FieldSelectProps) {
  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<HTMLButtonElement>) => {
    setTouched();
    // setFocus(false);
  };

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

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

  const controlLabel = control.label && label(control.label);
  return (
    state.flags.hidden ? (
      <input type="hidden" value={valueToString(state.value)} />
    ) : (
      <Field state={state} className={getClassNames({ required: control.required && !control.disabled })}>
        <Select
          name={uniqueName}
          value={control.value}
          options={control.options}
          placeholder={control.placeholder && label(control.placeholder)}
          onChange={onChange}
          onFocus={onFocus}
          onBlur={onBlur}
        >
          {controlLabel && (
            <Select.Label htmlFor={uniqueName}>{controlLabel}</Select.Label>
          )}
          <Select.Select
            required={state.errors.some(x => x.key === 'required')}
            disabled={state.flags.disabled || state.flags.readonly}
            aria-invalid={state.flags.invalid}
            aria-describedby={`${uniqueName}-error`}
          >
            {icon || <IconChevronDown />}
          </Select.Select>
          <Select.Popover gutter={4} sameWidth data-lenis-prevent>
            {control.options && control.options.map((option, i) => (
              <Select.Option key={i} value={option.id.toString()}>
                {option.name as string}
              </Select.Option>
            ))}
          </Select.Popover>
          <FieldError state={state} label={controlLabel} id={`${uniqueName}-error`} />
        </Select>
        {control.customData?.after && (
          control.customData.after
        )}
      </Field>
    )
  );
}
