import React, { useReducer, useEffect, useState, Fragment } from 'react'
import { RouteComponentProps } from 'react-router'
import { reducer, initialState, getLayersAction, updateLayerAction, Item } from './reducer'
import VectorShow from '../components/VectorShow'

type Attr = 'lineColor' | 'lineWidth' | 'fillColor'

function StyleEdit(props: RouteComponentProps) {
  let [state, dispatch] = useReducer(reducer, initialState)
  let layers = Object.keys(state)
  let [layer, setLayer] = useState('')
  let params = props.match.params as any
  let style = (layer && state[layer]) as Item

  useEffect(() => { getLayersAction(dispatch, params.id) }, [0])
  useEffect(() => { layer || setLayer(layers[0]) }, [state])

  const changeHandle = (attr: Attr) => (ev: React.ChangeEvent<HTMLInputElement>) => {
    updateLayerAction(dispatch, layer, {
      ...style,
      [attr]: ev.target.value
    })
  }

  return (
    <div>
      <select value={layer} onChange={ev => setLayer(ev.target.value)}>
        {layers.map(layer => <option value={layer} key={layer}>{layer}</option>)}
      </select>
      {style && (
        <Fragment>
          <input type="color" value={style.fillColor} onChange={changeHandle('fillColor')} />
          <input type="color" value={style.lineColor} onChange={changeHandle('lineColor')} />
          <input type="number" value={style.lineWidth} onChange={changeHandle('lineWidth')} />
        </Fragment>
      )}
      {style && <VectorShow {...style} height={3000} />}
    </div>
  )
}

export default StyleEdit