import * as React from 'react';

import { Wrapper, SelectStyled, Label } from './Select.styled';
import Icons from '../Icons';

export interface IProps {
  options?: any;
  label: string;
  onChange: (e?: any) => any;
}

export default class Select extends React.PureComponent<IProps> {
  state = {
    selectedValue: '',
    degree: 180,
  }

  renderHTMLOptions = () => this.props.options
    .map((item: { value: string; label: string }) => (
      <option value={item.value}>{item.label}</option>
    ))

  handleSelectChange = ({ currentTarget: { value } }: React.ChangeEvent<HTMLSelectElement>) => {
    this.setState({ selectedValue: value });

    if (value !== 'hide') {
      this.props.onChange(value);
      return;
    }

    this.props.onChange(undefined);
  };

  isInvalid = () => this.state.selectedValue === 'hide';

  render () {
    const { selectedValue, degree } = this.state;
    const { label } = this.props;

    return (
      <Wrapper>
        <SelectStyled
          onChange={this.handleSelectChange}
          onBlur={() => this.setState({ degree: 180 })}
        >
          <option value='hide'>{label}</option>
          {this.renderHTMLOptions()}
        </SelectStyled>
        <Label active={(!this.isInvalid() && selectedValue)}>{label}</Label>
        <Icons.Arrow degree={degree} width={20} height={20} />
      </Wrapper>
    );
  }
}
