import { ReactNode } from 'react'
import styles from './dropdownField.module.scss'
import classNames from 'classnames'
import selfless from '@komi-app/selfless'
import { DropdownItem, itemText } from '../Dropdown'

export type DropdownFieldProps = {
  keyword?: string
  placeholder: string
  suffixIcon?: ReactNode
  disabled?: boolean
  hasError?: boolean
  expanded?: boolean
  selectedItems?: DropdownItem[]
  multiLabel?: MultiLabel
} & React.ButtonHTMLAttributes<HTMLButtonElement>

export interface DropdownFieldViewProps
  extends Omit<DropdownFieldProps, 'selectedItems'> {
  fieldClassName: string
  labelClassName: string
  label: string
}

export type MultiLabel = (
  items: DropdownItem[]
) => `${number}${string}` | `${string}${number}${string}` | `${string}${number}`

export const DEFAULT_MULTI_LABEL: MultiLabel = (items: DropdownItem[]) => {
  const firstValue = items[0]

  if (typeof firstValue === 'string') {
    return `${firstValue} + ${items.length - 1} items`
  } else {
    return `${firstValue.label} + ${items.length - 1} items`
  }
}

export const useDropdownField = ({
  keyword,
  selectedItems,
  placeholder,
  disabled,
  hasError,
  multiLabel = DEFAULT_MULTI_LABEL,
  ...props
}: DropdownFieldProps) => ({
  placeholder,
  label:
    (selectedItems &&
      (selectedItems.length === 1
        ? itemText(selectedItems[0])
        : selectedItems.length > 1
          ? multiLabel(selectedItems)
          : '')) ||
    keyword ||
    placeholder,
  fieldClassName: classNames(styles.dropdownField, {
    [styles.dropdownField__disabled]: disabled,
    [styles.dropdownField__error]: hasError
  }),
  labelClassName: classNames(styles.label, {
    [styles.label__placeholder]: selectedItems && !selectedItems?.length,
    [styles.label__keyword]: !!selectedItems?.length
  }),
  disabled,
  ...props
})

export const DropdownFieldView = ({
  label,
  expanded,
  disabled,
  suffixIcon,
  fieldClassName,
  labelClassName,
  ...props
}: DropdownFieldViewProps) => (
  <button
    className={classNames(fieldClassName, {
      [styles.dropdownField__expanded]: expanded
    })}
    disabled={disabled}
    aria-labelledby="select button"
    aria-haspopup="listbox"
    aria-expanded={expanded}
    {...props}
  >
    <span className={labelClassName}>{label}</span>
    {suffixIcon}
  </button>
)

export const DropdownField = selfless(DropdownFieldView, useDropdownField)
export default DropdownField
