import React, { useState } from 'react'
import styled from 'styled-components'
import { IJsonSchema } from '../../types/IJsonSchema'
import { InputWrapper } from '../InputWrapper/InputWrapper'

export interface PercentageInputProps {
  label?: string;
  value: number|string
  placeholder?: string
  name: string
  jsonSchema?:IJsonSchema
  onChange: (change: number|null ) => void
  css?: string
}

export const PercentageInput = ({ 
  value='',
  label,
  placeholder,
  name,
  jsonSchema,
  onChange,
  css }: PercentageInputProps):JSX.Element => {

  const [localValue,setLocalValue] = useState(value===''?'':String(Number(value)*100))
  
  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = event.target
    setLocalValue(value.replace(/[^.0-9]/g,'').replace(/%/g,''))
  }

  const handleBlur = ()=>{
    if(localValue === '') return onChange(null)
    onChange(Number(localValue)/100)
  }

  return (
    <InputWrapper label={label} 
      jsonSchema={jsonSchema} 
      value={Number(localValue)/100}>
      <Wrapper css={css}>
        <StyledPercentageInput
          type='percentage'
          value={localValue||''}
          name={name}
          placeholder={placeholder}
          onBlur={handleBlur}
          onChange={handleChange}
        />
        <Icon>%</Icon>
      </Wrapper>
    </InputWrapper>
  )
}

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

  ${(p) => p.css}
`

const Icon = styled.span`
    font-size: 1rem;
  font-weight: 400;
  line-height: 1;
  color: darkgray;
  text-align: center;
  position: absolute;
  right: 10px;
  pointer-events: none;
  width: 20px;
`

const StyledPercentageInput = styled.input`
  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;
  appearance: none;
  resize: none;
  box-sizing: border-box;
    font-size: 1rem;
  color: #000;
  text-align: left;
  min-height: 36px;
  padding-left: 5px;
  border-radius: 4px;
  border: none;
  width: 100%;
  background-color: #ffffff;
  transition: border-color 100ms ease 0s;
   
  &:focus {
    outline: none;
    border-color: #228be6;
  }
`