import PropTypes from 'prop-types'
import { Flex, Typography, Input } from 'antd'
import CountryDisplay from './CountryDisplay'
import CountrySelect from './CountrySelect'

const { Text } = Typography

const ADDRESS_FIELDS = [
  { key: 'building', label: 'Building' },
  { key: 'addressLine1', label: 'Line 1' },
  { key: 'addressLine2', label: 'Line 2' },
  { key: 'city', label: 'City' },
  { key: 'state', label: 'State' },
  { key: 'postcode', label: 'Postcode' },
  { key: 'country', label: 'Country', isCountry: true }
]

const AddressDisplay = ({
  value,
  isEditing = false,
  onChange,
  disabled = false
}) => {
  const address = value && typeof value === 'object' ? value : {}
  const hasAddress = ADDRESS_FIELDS.some(
    (f) => address[f.key] != null && address[f.key] !== ''
  )

  const handleFieldChange = (field, fieldValue) => {
    if (!onChange) return
    onChange({
      ...address,
      [field]: fieldValue
    })
  }

  if (!isEditing) {
    if (!hasAddress) {
      return <Text type='secondary'>n/a</Text>
    }

    return (
      <Flex vertical gap={4}>
        {ADDRESS_FIELDS.map(({ key, label, isCountry }) => {
          const fieldValue = address[key]
          if (fieldValue == null || fieldValue === '') return null

          return (
            <Flex key={key} gap={8} align='baseline'>
              {isCountry ? (
                <CountryDisplay countryCode={fieldValue} />
              ) : (
                <Text ellipsis alt={label}>
                  {fieldValue}
                </Text>
              )}
            </Flex>
          )
        })}
      </Flex>
    )
  }

  return (
    <Flex vertical gap={12}>
      {ADDRESS_FIELDS.map(({ key, label, isCountry }) =>
        isCountry ? (
          <Flex key={key} gap={8} align='center'>
            <CountrySelect
              placeholder={`Select ${label.toLowerCase()}`}
              value={address[key]}
              onChange={(v) => handleFieldChange(key, v)}
              disabled={disabled}
              style={{ flex: 1 }}
              alt={label}
            />
          </Flex>
        ) : (
          <Flex key={key} gap={8} align='center'>
            <Input
              placeholder={label}
              value={address[key] ?? ''}
              onChange={(e) => handleFieldChange(key, e.target.value)}
              disabled={disabled}
              style={{ flex: 1 }}
              alt={label}
            />
          </Flex>
        )
      )}
    </Flex>
  )
}

AddressDisplay.propTypes = {
  value: PropTypes.shape({
    building: PropTypes.string,
    addressLine1: PropTypes.string,
    addressLine2: PropTypes.string,
    city: PropTypes.string,
    state: PropTypes.string,
    postcode: PropTypes.string,
    country: PropTypes.string
  }),
  isEditing: PropTypes.bool,
  onChange: PropTypes.func,
  disabled: PropTypes.bool
}

export default AddressDisplay
