import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import Icon from '../Icon';
import Loader from '../Loader';
import IconButton from '../Controls/IconButton';

const SearchIcon = styled(Icon)`
  margin-right: 8px;
`;

const Root = styled.div`
  display: flex;
  width: ${props => props.width || '100%'};
  align-items: center;
  padding: 0 14px 0 20px;
  height: 48px;
  border-radius: 6px;
  border: 1px solid ${props => props.theme.colors.grey.v300};
  background: ${props => props.theme.colors.white};
`;

const Input = styled.input`
  width: 100%;
  height: 100%;
  padding: 0 14px 0 0;
  border: none;
  font-size: 18px;
  font-family: ${props => props.theme.fonts.text};
  font-weight: 400;
  background: transparent;
  outline: none;

  &::placeholder {
    color: ${props => props.theme.colors.grey.v400};
    font-weight: 400;
  }

  &::-webkit-search-cancel-button {
    -webkit-appearance: none;
    cursor: pointer;
  }
`;

const InputEndContainer = styled.div`
  display: flex;
  align-items: center;
`;

function Searchbar({ value, placeholder, width, loading, endAdornment, onChange, className }) {
  const _onChange = event => {
    onChange(event.target.value, event);
  };

  function renderInputEnd() {
    if (loading) {
      return <Loader size="small" />;
    }
    if (value?.length > 0) {
      return (
        <IconButton
          icon="Cross"
          onClick={() => {
            onChange('');
          }}
        />
      );
    }
    return <SearchIcon iconSize={20} name="MagnifyingGlass" />;
  }

  return (
    <Root width={width} className={className}>
      <Input type="search" value={value} disabled={loading} onChange={_onChange} placeholder={placeholder} />
      <InputEndContainer>{renderInputEnd()}</InputEndContainer>
      {endAdornment}
    </Root>
  );
}

Searchbar.propTypes = {
  value: PropTypes.string,
  placeholder: PropTypes.string,
  loading: PropTypes.bool,
  width: PropTypes.string,
  endAdornment: PropTypes.node,
  onChange: PropTypes.func,
  className: PropTypes.string
};

Searchbar.defaultProps = {
  value: '',
  width: '100%'
};

export default Searchbar;
