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

import ImageGallery from './ImageGallery'

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

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

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

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

  const AttributeInner = memo(function AttributeInner({ props }) {
    const key = props.key;
    const type = database[id].type;
    if (type === "image" && key === "width" || type === "image" && key === "height") return;

    const [value, setValue] = useState(props.value);

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

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

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

    return (
      <Item>
        <Title>[ {props.key} ]</Title>
        <input className='w-100' type='text' value={value} onChange={changeHandle} onBlur={blurHandle} />
        <img src={props.value} alt="Preview" width={"100"} height={"auto"} />
        {key === "src" && <ImageGallery id={id} />}
      </Item>
    )
  });

  const attributeList = Object.keys(props);

  return (
    <>
      <Heading>Attribute</Heading>
      {
        attributeList.map((key, index) => {
          const attr = {
            key: key,
            value: props[key]
          }
          return <AttributeInner props={attr} key={index} />
        })
      }
    </>
  )
}

export default Attribute