import { useState, memo } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { updateDatabase } from '../../database/database'
import styled from 'styled-components'

import Property from './Properties'

const Heading = styled.h3`
  font-size: 18px;
  line-height: 24px;
  text-align: center;
  padding: 10px;
  margin-top: 10px;
`

const Item = styled.div`
  position: relative;
  padding: 10px;
`

const Title = styled.h4`
  font-size: 16px;
  line-height: 24px;
  font-weight: 500;
  margin-bottom: 8px;
`

function StyleManager({ id, props }) {
  const database = useSelector((state) => state.database.value);
  const dispatch = useDispatch();

  const StyleInner = memo(function StyleInner({ props }) {
    const key = props.key;
    const [value, setValue] = useState(props.value);

    const changeHandle = (evt) => {
      setValue(evt.target.value);
    }

    const blurHandle = () => {
      const initalValue = database[id].styles[key];
      if (value === initalValue) return;

      const newStyles = { ...database[id].styles, [key]: value };
      const newParams = { ...database[id], styles: newStyles };
      const newDatabase = { ...database, [id]: newParams };
      dispatch(updateDatabase(newDatabase));
    }

    const propertyProps = {
      id: id,
      type: key,
      value: value
    }

    return (
      <Item>
        <Title>[ {key} ]</Title>
        <input className='w-100' type='text' value={value} onChange={changeHandle} onBlur={blurHandle} />
        <Property props={propertyProps} />
      </Item>
    )
  });

  const styleList = Object.keys(props);

  return (
    <>
      <Heading>Style</Heading>
      {
        styleList.map((key, index) => {
          const attr = {
            key: key,
            value: props[key]
          }
          return <StyleInner props={attr} key={index} />
        })
      }
    </>
  )
}

export default StyleManager