import React from 'react'
import { InputWrapper } from '../InputWrapper/InputWrapper'
import styled from 'styled-components'
import { IJsonSchema } from '../../types/IJsonSchema'
import arrows from './arrows.png'

export type DropdownProps = {
  name: string
  label?: string
  value?: string|number
  options?: { label: string, value: string|number }[]
  placeholder?: string
  /**
   * schema for validation
   */
  jsonSchema?: IJsonSchema
  /**
   * custom styling for password input
   */
  css?: string
  onChange: (change:string | number ) => void
}

export const Dropdown = ({ 
  name,
  value,
  label,
  jsonSchema,
  options,
  placeholder,
  onChange,
  css }: DropdownProps):JSX.Element => {

  const handleChange = (event:React.ChangeEvent<HTMLSelectElement>) => {
    onChange(event.target.value)
  }

  return (
    <InputWrapper label={label} jsonSchema={jsonSchema} value={value}>
      <Wrapper css={css}>
        <Select
          name={name}
          value={value||'placeholder'}
          onChange={handleChange}>
          {placeholder && <StyledPlaceholder value="placeholder" hidden disabled>{placeholder}</StyledPlaceholder>}
          {options?.map(({ value,label },index) => {
            return (
              <option 
                key={index}
                value={value}>{label}</option>
            )
          })}
        </Select>
        <Icon src={arrows}></Icon>
      </Wrapper>
    </InputWrapper>
  )
}

const Wrapper = styled.div<{css?:string}>`
  position: relative;
  display: flex;
  align-items: center;
  width: 100%;

  ${(p) => p.css}
`
const Select = styled.select`
  font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji;
  height: 36px;
  -webkit-tap-highlight-color: transparent;
  line-height: 34px;
  -webkit-appearance: none;
  outline: none;
  -moz-appearance: none;
  -ms-appearance: none;
  appearance: none;
  resize: none;
  box-sizing: border-box;
    font-size: 1rem;
  width: 100%;
  color: #000;
  display: block;
  text-align: left;
  min-height: 36px;
  /* padding-left: 12px; */
  padding-right: 30px;
  border-radius: 4px;
  border: none;
  background-color: #fff;
  -webkit-transition: border-color 100ms ease;
  transition: border-color 100ms ease;
  cursor: pointer;
  
    &:focus {
      outline: none;
      border-color: #228be6;
    }
`
const StyledPlaceholder = styled.option``
const Icon = styled.img`
  position: absolute;
  right: 10px;
  pointer-events: none;
  width: 20px;
`