import React, { useEffect, useMemo } from 'react'
import { cardInstantAtomFamily, cardInstantAtomsAtom } from '../../store'
import { atomWithReducer, useReducerAtom } from 'jotai/utils'
import { useAtom } from 'jotai'

const Form = ({ node, cardInstantAtom }) => {
  const fields = useMemo(() => {
    return node?.properties?.fields
  }, [node, node.id])

  const dataReducer = (prev, payload) => {
    return { ...prev, ...payload }
  }

  const [cardInstantData, dispatchCardInstantData] = useReducerAtom(cardInstantAtom, dataReducer)

  const onChange = (value, field) => {
    const content = cardInstantData.content ?? {}
    content[field.id] = {
      ...content[field.id],
      label: field.value,
      value
    }
    dispatchCardInstantData({ content })
  }

  return (
    <div className="flex flex-col items-center w-full">
      {fields.map((field, i) => (
        <label key={i} className="form-control w-full max-w-xs">
          <div className="label">
            <span className="label-text">{field.value}</span>
          </div>
          <input type="text" placeholder={field.value} className="input input-bordered w-full max-w-xs" value={cardInstantData?.[field.value]} onChange={(e) => onChange(e.target.value, field)} />
        </label>
      ))}
    </div>
  )
}
export default React.memo(Form)