import type { ComboboxStore } from '@mantine/core';

import { ActionIcon, Loader, TextInput } from '@mantine/core';
import { IconX } from '@tabler/icons-react';
import React, { forwardRef } from 'react';

interface BoxerTargetProps {
  clearable?: boolean;
  combobox: ComboboxStore;
  disabled?: boolean;
  error?: string;
  isFetching?: boolean;
  label?: string;
  leftSection?: React.ReactNode;
  onBlur: () => void;
  onClear: () => void;
  onSearch: (event: React.ChangeEvent<HTMLInputElement>) => void;
  placeholder?: string;
  search: string;
}

const BoxerTarget = forwardRef<HTMLInputElement, BoxerTargetProps>((props, ref) => {
  const {
    clearable = true,
    combobox,
    disabled,
    error,
    isFetching,
    label,
    leftSection,
    onBlur,
    onClear,
    onSearch,
    placeholder,
    search,
  } = props;

  const rightSection = isFetching ? (
    <Loader size="xs" />
  ) : search && clearable ? (
    <ActionIcon
      onClick={(e) => {
        e.stopPropagation();
        onClear();
      }}
      size="sm"
      variant="subtle"
    >
      <IconX size={16} />
    </ActionIcon>
  ) : null;

  return (
    <TextInput
      disabled={disabled}
      error={error}
      label={label}
      leftSection={leftSection}
      onBlur={onBlur}
      onChange={onSearch}
      onClick={() => combobox.openDropdown()}
      onFocus={() => combobox.openDropdown()}
      placeholder={placeholder}
      ref={ref}
      rightSection={rightSection}
      value={search}
    />
  );
});

BoxerTarget.displayName = 'BoxerTarget';

export default BoxerTarget;
