import { MybringCustomerAndServices } from '../model/models'
import React, { FC } from 'react'
import { SelectControl } from '@wordpress/components'
import { useI18n } from '@wordpress/react-i18n'
type SelectControlOption = NonNullable<
  React.ComponentProps<typeof SelectControl>['options']
>[number]

export declare interface CustomerSelectorProps {
  customers: Array<MybringCustomerAndServices>
  selectedCustomer?: string
  onSelect: (customerNumber: string) => void
  className?: string
  label?: string
}

const CustomerSelector: FC<CustomerSelectorProps> = ({
  customers,
  selectedCustomer,
  onSelect,
  className,
  label,
}) => {
  const { __ } = useI18n()

  const getOptions = () => {
    return [
      {
        label: __('Select customer number', 'posten-bring-checkout'),
        value: '',
        disabled: true,
      } as SelectControlOption,
    ].concat(
      customers.map(
        (customer): SelectControlOption => ({
          label: customer.displayName,
          value: customer.customerNumber,
          disabled: false,
        })
      )
    )
  }

  return customers?.length > 1 ? (
    <SelectControl
      label={label}
      value={selectedCustomer || ''}
      options={getOptions()}
      onChange={onSelect}
      className={`bring-select${className ? ' ' + className : ''}`}
      suffix={''}
      __nextHasNoMarginBottom={true}
      __next40pxDefaultSize={true}
    />
  ) : null
}

export default CustomerSelector
