import React from 'react'
import classNames from 'classnames'
import { bool, node, oneOfType, string, object, oneOf, func } from 'prop-types'

import { Icon } from '@swrve/icons'

import Checkbox from './checkbox'

const CheckboxListItem = ({
  children,
  onChange,
  theme,
  checked,
  disabled,
  label,
  labelPosition,
  className,
  noBackground,
  textColor = 'text-regentGrey',
  withBorder = false,
  icon,
  ...props
}) => {
  const isLabelLeftAligned = labelPosition === 'left'

  const containerStyles = classNames(
    `sw-control-label flex-col`,
    { [textColor]: !checked },
    { [`border-${theme}-100`]: checked && withBorder },
    { [`bg-${theme}-10`]: checked && !disabled && !noBackground },
    { [`text-${theme}-100`]: checked && !disabled },
    { [`hover:bg-${theme}-10`]: !disabled && !noBackground },
    { [`hover:text-${theme}-100`]: !disabled },
    className
  )

  const labelStyles = classNames('flex flew-row w-full items-center', {
    'justify-between': isLabelLeftAligned
  })

  const textStyles = classNames(
    'text-sm',
    { 'order-0': isLabelLeftAligned },
    { 'pl-4': !isLabelLeftAligned }
  )

  const checkboxStyles = classNames({ 'order-1': isLabelLeftAligned })

  return (
    <label className={containerStyles} {...props}>
      <div className={labelStyles}>
        <Checkbox
          onChange={onChange}
          checked={checked}
          disabled={disabled}
          theme={theme}
          className={checkboxStyles}
        />
        <span className={textStyles}>
          {icon && <Icon className="flex-shrink-0 mr-2" name={icon} size="small" />}
          {label}
        </span>
      </div>
      {children}
    </label>
  )
}

CheckboxListItem.displayName = 'Checkbox'

CheckboxListItem.propTypes = {
  /** Set to true to allow parent to control background colours. */
  noBackground: bool,
  /** Determine wether or not checkbox is checked */
  checked: bool,
  /** Label for checkbox */
  children: node,
  /** Extra css classes to extend from external */
  className: oneOfType([string, object]),
  /** Determine wether or not checkbox is disabled */
  disabled: bool,
  /** Name of icon to display in front of label */
  icon: string,
  /** Checkbox onchange handler */
  labelPosition: oneOf(['left', 'right']),
  /** Checkbox onchange handler */
  onChange: func.isRequired,
  /** Determines the border style */
  theme: oneOf(['primary', 'secondary']).isRequired
}

CheckboxListItem.defaultProps = {
  checked: false,
  className: '',
  disabled: false,
  noBackground: false,
  theme: 'secondary',
  labelPosition: 'right',
  onChange: () => {}
}

export default CheckboxListItem
