import * as React from "react"
import styled from "styled-components"

import { InputSingleLine } from "./Input"

const Select = styled.select`
  opacity: 0;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: calc(100% - 0px);
  height: 100%;
  -webkit-appearance: none;
`
const ValueInput = styled(InputSingleLine)`
  text-overflow: ellipsis;
  padding-right: 20px;
  &:disabled {
    opacity: 1;
    color: ${(props) => props.theme.matteBlack};
  }
  -webkit-appearance: none;
` as any
const Option = styled.option`
  width: auto;
`
const UISelectContainer = styled.div`
  position: relative;
  // margin: 0 3px;
  left: 0;
  right: 0;
`
const Arrow = styled.span`
  border-color: #999 transparent transparent;
  border-style: solid;
  border-width: 5px 5px 2.5px;
  display: inline-block;
  height: 0;
  width: 0;
  position: absolute;
  right: 10px;
  top: 50%;
  pointer-events: none;
  transform: translateY(-50%);
`

export type SelectInputOptions = {
  value: any
  label: any
}
export interface SelectInputAttributePropType
  extends React.InputHTMLAttributes<any> {
  onChange: (value) => void
  options: SelectInputOptions[]
  value: any

  containerClassName?: string
  containerStyle?: any
  label?: string
  error?: any
}

export class ReactSaviorSelector extends React.Component<
  SelectInputAttributePropType,
  any
> {
  public onChange = (e) => {
    this.props.onChange(e.target.value)
  }
  get selectedItem() {
    for (const item of this.props.options) {
      if (this.props.value === item.value) {
        return item
      }
    }
    return { label: "" }
  }
  public render() {
    const selectedValue = this.props.value || this.props.placeholder
    return (
      <UISelectContainer
        className={this.props.containerClassName}
        style={this.props.containerStyle}
      >
        <ValueInput
          disabled
          placeholder={this.props.placeholder}
          fluid
          readOnly
          error={this.props.error}
          value={this.selectedItem.label}
        />
        <Select
          value={selectedValue}
          disabled={this.props.disabled}
          onChange={this.onChange}
          name={this.props.name || "name-is-not-set"}
        >
          <option value={this.props.placeholder} disabled>
            {this.props.placeholder}
          </option>
          {this.props.options.map((option) => (
            <Option value={option.value} key={option.value}>
              {option.label}
            </Option>
          ))}
        </Select>
        <Arrow />
      </UISelectContainer>
    )
  }
}
export default ReactSaviorSelector
