import { useState, useEffect } from 'react'
import arrayMove from 'array-move'
import BlockInputs from './BlockInputs'
import { SortableList } from '../../sortable'
import { SubBlockFragment } from '../../gql'

const BlockInstanceInputs = ({
  name,
  value,
  onChange
}: {
  name: string
  value: SubBlockFragment[]
  onChange: GenericEventHandler
}) => {
  const [state, setState] = useState(value.map((item, index) => index))
  console.log(name, value)

  function onSortEnd({
    oldIndex,
    newIndex
  }: {
    oldIndex: number
    newIndex: number
  }) {
    const newOrder = arrayMove(state, oldIndex, newIndex)
    setState(newOrder)
  }

  useEffect(() => {
    const missingIndices = []
    for (let idx = 0; idx < value.length - 0; idx++) {
      if (!state.includes(idx)) missingIndices.push(idx)
    }
    setState([...state, ...missingIndices])
  }, [value])

  const items = state.map((order, index) => {
    const item = value[order]
    console.log({ value, order, item })
    return (
      <BlockInputs
        key={item.order}
        name={`${name}.${index}.block`}
        value={item.block}
        onChange={onChange}
      />
    )
  })

  return (
    <SortableList
      items={items}
      onSortEnd={onSortEnd}
      useDragHandle
      lockAxis={'y'}
    />
  )
}

export default BlockInstanceInputs
