import { SelectControl } from '@wordpress/components'
import React, { FC, useEffect, useState } from 'react'
import {
  MybringCustomerAndServices,
  SelectOption,
  ServiceDetails,
} from '../model/models'
import { useI18n } from '@wordpress/react-i18n'

export declare interface ShippingOptionSelectorProps {
  selectedShippingOption?: string
  setSelectedShippingOption: (selected: string) => void
  availableServices: Array<ServiceDetails>
  selectedCustomer?: string
  customersAndServices: Array<MybringCustomerAndServices>
  preSelectedShippingOption?: string
  className?: string
  label?: string
}

const ShippingOptionSelector: FC<ShippingOptionSelectorProps> = ({
  availableServices,
  preSelectedShippingOption,
  selectedCustomer,
  customersAndServices,
  selectedShippingOption,
  setSelectedShippingOption,
  className,
  label,
}) => {
  const { __ } = useI18n()
  const [options, setOptions] = useState<Array<SelectOption>>([])

  useEffect(() => {
    const mybringCustomer = customersAndServices?.find(
      c => selectedCustomer === c.customerNumber
    )

    const availableOptions = availableServices
      ?.filter(
        option =>
          mybringCustomer?.services.find(
            s => s.serviceCode === option.service_id
          ) || false
      )
      .map(
        option =>
          ({
            label:
              option.service_id === preSelectedShippingOption
                ? `${option.name} - ${__(
                    'Customers choice',
                    'posten-bring-checkout'
                  )}`
                : option.name,
            value: option.service_id,
          }) as SelectOption
      )

    if (!preSelectedShippingOption) {
      availableOptions.push({
        label: __('No shipping option selected', 'posten-bring-checkout'),
        value: '',
        disabled: true,
      })
    } else if (
      availableOptions?.length === 0 &&
      customersAndServices?.length > 0 &&
      selectedCustomer
    ) {
      availableOptions.push({
        label: __('No available shipping options', 'posten-bring-checkout'),
        value: '',
        disabled: true,
      })
    } else if (
      selectedCustomer &&
      preSelectedShippingOption &&
      !availableOptions.find(
        option => option.value === preSelectedShippingOption
      )
    ) {
      if (
        !availableOptions.find(
          option => option.value === selectedShippingOption
        )
      ) {
        setSelectedShippingOption('')
      }
      availableOptions?.push({
        label: __('No shipping option selected', 'posten-bring-checkout'),
        value: '',
        disabled: true,
      })
    } else if (
      selectedShippingOption === '' &&
      availableOptions.find(
        option => option.value === preSelectedShippingOption
      )
    ) {
      setSelectedShippingOption(preSelectedShippingOption || '')
    } else if (!selectedCustomer) {
      availableOptions?.push({
        label: __(
          'Select customer to see available shipping options',
          'posten-bring-checkout'
        ),
        value: '',
        disabled: true,
      })
    }

    setOptions(availableOptions)
  }, [
    availableServices?.length,
    selectedCustomer,
    customersAndServices?.length,
    preSelectedShippingOption,
    customersAndServices,
    availableServices,
    selectedShippingOption,
    __,
    setSelectedShippingOption,
  ])

  return (
    <SelectControl
      label={label}
      value={selectedShippingOption || ''}
      options={options}
      onChange={setSelectedShippingOption}
      className={`bring-select${className ? ' ' + className : ''}`}
      suffix={''}
      __nextHasNoMarginBottom={true}
	  __next40pxDefaultSize={true}
    />
  )
}

export default ShippingOptionSelector
