import { Country } from '../../constans/country';
import {
  CountrySelectField,
  CountrySelectFieldProps,
} from '../../form/CountrySelectField/CountrySelectField';
import { FormField } from '../../form/FormField/FormField';
import { assertEmptyObject } from '../../utils/assertEmptyObject';
import { makeTestId } from '../../utils/makeTestId';
import { CommonFormikProps } from '../common/types';
import { useFormikFieldsProps } from '../hooks/useFormikFieldsProps';

export interface FormikCountrySelectFieldProps
  extends CommonFormikProps<Country | null>,
    Pick<CountrySelectFieldProps, 'placeholder' | 'cleanable'> {}

/**
 * Formik field that allows selecting country.
 *
 * ```tsx
 * import { FormikCountrySelectField } from 'ui-kit';
 *
 * <FormikCountrySelectField name="country" label="Country" />
 * ```
 */
export function FormikCountrySelectField(props: FormikCountrySelectFieldProps) {
  const { id, formFieldProps, controlProps } = useFormikFieldsProps<CountrySelectFieldProps>(props);

  const {
    className,
    descriptionMessageId,
    description,
    errorMessageId,
    error,
    label,
    onHintClick,
    hintText,
    requirement,
    testId,
    ...restFormFieldProps
  } = formFieldProps;
  assertEmptyObject(restFormFieldProps);

  const {
    value,
    onChange,
    onBlur,
    placeholder,
    disabled,
    ariaErrorMessage,
    ariaDescribedBy,
    ariaLabel,
    ariaInvalid,
    multiple,
    trigger,
    async,
    noOptionsMessage,
    hideSearch,
    optionToSearchString,
    required,
    ariaRequired,
    cleanable,
    ...restControlProps
  } = controlProps;
  assertEmptyObject(restControlProps);

  return (
    <FormField
      className={className}
      description={description}
      descriptionMessageId={descriptionMessageId}
      error={error}
      errorMessageId={errorMessageId}
      hintText={hintText}
      id={id}
      label={label}
      onHintClick={onHintClick}
      requirement={requirement}
      testId={testId}
    >
      <CountrySelectField
        ariaDescribedBy={ariaDescribedBy}
        ariaErrorMessage={ariaErrorMessage}
        ariaInvalid={ariaInvalid}
        ariaLabel={ariaLabel}
        ariaRequired={ariaRequired}
        async={async}
        cleanable={cleanable}
        disabled={disabled}
        hideSearch={hideSearch}
        id={id}
        multiple={multiple}
        noOptionsMessage={noOptionsMessage}
        onBlur={onBlur}
        onChange={onChange}
        optionToSearchString={optionToSearchString}
        placeholder={placeholder}
        required={required}
        testId={makeTestId(testId, 'country-select-field')}
        trigger={trigger}
        value={value}
      />
    </FormField>
  );
}
