import { bool, func, node, number, oneOf, oneOfType, string } from 'prop-types';
import React from 'react';
import Icon from '../Icon/index';
import css from '@styled-system/css';
import styled from '@emotion/styled';
import { Box } from '../Layout';

const StyledSelect = styled('select')(
  css({
    borderRadius: 'input',
    paddingRight: '30px',
    paddingLeft: '10px',
    outline: 'none',
    boxShadow: 'none',
    border: 'none',
    fontSize: 'input',
    color: 'input',
    justifyContent: 'center',
    alignItems: 'center',
    background: 'transparent',
    width: '100%',
    height: '100%',
  }),
  ({ appearance, theme, error, disabled }) => ({
    borderStyle: 'solid',
    color: disabled ? theme.colors.disabled : error ? theme.colors.error : theme.colors.input,
    borderColor: error ? theme.colors.borderError : theme.colors.border,
    borderWidth: appearance === 'borderless' ? 0 : 1,
    ':not(:focus-within):hover': {
      borderColor: theme.colors.borderActive,
    },
    ':focus-within': {
      outline: 'none',
      borderColor: theme.colors.borderFocus,
      boxShadow: `inset 0 0 0 1px ${theme.colors.borderFocus}`,
    },
    cursor: disabled ? 'not-allowed' : 'default',
    backgroundColor: disabled
      ? theme.colors.backgroundDisabled
      : appearance === 'borderless'
      ? theme.colors.backgroundDisabled
      : 'white',
    appearance: 'none',
  }),
);

const Select = ({
  children,
  onChange,
  value,
  className,
  error,
  width = 'auto',
  height = '40px',
  disabled,
  appearance = 'default',
  ...rest
}) => (
  <Box color="input" width={width} height={height} position="relative">
    <StyledSelect
      error={error}
      disabled={disabled}
      value={value}
      onChange={onChange}
      appearance={appearance}
      {...rest}
    >
      {children}
    </StyledSelect>
    <Icon
      name="arrow-down"
      size={9}
      style={{
        pointerEvents: 'none',
        position: 'absolute',
        right: 10,
        top: 0,
        bottom: 0,
        margin: 'auto',
      }}
    />
  </Box>
);

export default Select;

Select.propTypes = {
  children: node.isRequired,
  onChange: func,
  value: oneOfType([string, number]),
  className: oneOfType([string, number]),
  error: oneOfType([bool, string]),
  height: string,
  disabled: bool,
  appearance: oneOf(['default', 'borderless']),
};
