import { Select } from 'antd';
import type { SelectProps } from 'antd';
import { useMemo } from 'react';
import type { SelectOptionItem, SelectUIProps } from './types';

function normalizeKeyword(text: string) {
  return text.trim().toLowerCase();
}

export function SelectUI({
  data,
  value,
  defaultValue,
  onChange,
  formatLabel,
  showSearch = true,
  allowClear = true,
  placeholder = '항목을 선택하세요',
  ...restProps
}: SelectUIProps) {
  const options = useMemo<SelectProps<string>['options']>(
    () =>
      data.map((item) => ({
        value: item.code,
        label: formatLabel ? formatLabel(item) : item.value,
        item,
      })),
    [data, formatLabel],
  );

  const itemMap = useMemo(
    () =>
      new Map<string, SelectOptionItem>(data.map((item) => [item.code, item])),
    [data],
  );

  return (
    <Select<string>
      {...restProps}
      value={value}
      defaultValue={defaultValue}
      showSearch={showSearch}
      allowClear={allowClear}
      placeholder={placeholder}
      options={options}
      optionFilterProp="label"
      filterOption={(input, option) =>
        normalizeKeyword(String(option?.label ?? '')).includes(normalizeKeyword(input))
      }
      onChange={(nextCode) => {
        onChange?.(nextCode, nextCode ? itemMap.get(nextCode) : undefined);
      }}
    />
  );
}
