import FormatSelector from './FormatSelector'
import { TextInput } from '../../form'
import BlockInstanceInputs from './BlockInstanceInputs'
import { emptyBlockInstance } from '../utils'
import ExerciseInstanceInputs from './ExerciseInstanceInputs'
import { TBlock } from '../types'

interface IBlockInputs {
  onChange: GenericEventHandler
  value: TBlock
  name: string
}

const BlockInputs = ({ onChange, value, name }: IBlockInputs) => {
  return (
    <>
      <TextInput
        name={`${name}.title`}
        label='Title'
        value={value.title}
        onChange={onChange}
      />
      <TextInput
        name={`${name}.description`}
        label='Description'
        value={value.description ?? ''}
        onChange={onChange}
      />
      <TextInput
        name={`${name}.duration`}
        label='Duration'
        value={value.duration ?? ''}
        type='number'
        onChange={onChange}
      />
      <FormatSelector
        name={`${name}.format`}
        value={value.format}
        onChange={onChange}
      />
      <TextInput
        name={`${name}.rest`}
        label='Rest'
        value={value.rest ?? ''}
        type='number'
        onChange={onChange}
      />
      <label>Blocks</label>
      {value.blocks && value.blocks.length > 0 && (
        <BlockInstanceInputs
          name={`${name}.blocks`}
          value={value.blocks}
          onChange={onChange}
        />
      )}
      <button
        onClick={event => {
          event.preventDefault()
          const newBlock = emptyBlockInstance({
            order: value.blocks ? value.blocks.length : 0
          })
          onChange({
            target: {
              type: 'custom',
              name: `${name}.blocks`,
              value: value.blocks ? [...value.blocks, newBlock] : [newBlock]
            }
          })
        }}
        type='button'
      >
        Add block
      </button>
      <label>Exercises</label>
      {value.exercises && value.exercises.length > 0 && (
        <ExerciseInstanceInputs
          name={`${name}.blocks`}
          value={value.exercises}
          onChange={onChange}
        />
      )}
      <button
        onClick={event => {
          event.preventDefault()
          const newExercise = empty({
            order: value.blocks ? value.blocks.length : 0
          })
          onChange({
            target: {
              type: 'custom',
              name: `${name}.blocks`,
              value: value.blocks ? [...value.blocks, newBlock] : [newBlock]
            }
          })
        }}
        type='button'
      >
        Add exercise
      </button>
    </>
  )
}

export default BlockInputs
