import { useCreateTrainingMutation, useUpdateTrainingMutation } from '../../gql'
import { useForm, TextInput, DateTimeInput, Checkbox } from '../../form'
import {
  emptyTraining,
  emptyBlockInstance,
  transformArrayToDB,
  diffDB
} from '../utils'
import TrainingTypeSelector from './TrainingTypeSelector'
import BlockInstanceInputs from './BlockInstanceInputs'
import { TTraining } from '../types'
import { transform } from 'lodash'
import Registrations from './Registrations'
import Ratings from './Ratings'

const EditTraining = ({ training }: { training?: TTraining }) => {
  const { values, touched, onChange, loadData } = useForm(
    training || emptyTraining()
  )
  const [createTraining, createData] = useCreateTrainingMutation()
  const [updateTraining, updateDate] = useUpdateTrainingMutation()

  return (
    <form
      onSubmit={ev => {
        ev.preventDefault()
        if (values.id.startsWith('++')) {
          const newValues = transform(values, transformArrayToDB)
          console.log({ newValues })
          createTraining({ variables: newValues })
        } else {
          const { id, ...changes } = diffDB(values, training || emptyTraining())
          const newValues = transform(changes, transformArrayToDB)
          if (Object.keys(newValues).length > 0) {
            console.log('saving changes', changes, newValues)
            updateTraining({
              variables: { where: { id: values.id }, data: newValues }
            })
          } else {
            console.log('no changes.')
          }
        }
      }}
    >
      <p>
        {values.createdAt} {values.id}
      </p>
      <TextInput
        name='title'
        label='Title'
        value={values.title}
        onChange={onChange}
      />
      <TrainingTypeSelector
        name='type'
        value={values.type}
        onChange={onChange}
      />
      <DateTimeInput
        name='trainingDate'
        label='Training date'
        value={values.trainingDate}
        onChange={onChange}
      />
      <TextInput
        name='location'
        label='Location'
        value={values.location}
        onChange={onChange}
      />
      <Registrations registrations={values.registrations} />
      <TextInput
        name='attendance'
        label='Attendance'
        type='number'
        value={values.attendance}
        onChange={onChange}
      />
      <Ratings ratings={values.ratings} />
      <Checkbox
        name='published'
        label='Published'
        value={values.published}
        onChange={onChange}
      />
      <label>Blocks</label>
      {values.blocks && (
        <BlockInstanceInputs
          name='blocks'
          value={values.blocks}
          onChange={onChange}
        />
      )}
      <button
        onClick={event => {
          event.preventDefault()
          const newBlock = emptyBlockInstance({
            order: values.blocks
              ? values.blocks.filter(block => !block.id.startsWith('--')).length
              : 0
          })
          onChange({
            target: {
              type: 'custom',
              name: 'blocks',
              value: values.blocks ? [...values.blocks, newBlock] : [newBlock]
            }
          })
        }}
        type='button'
      >
        Add block
      </button>
      <button type='submit' disabled={createData.loading}>
        Save
      </button>
      {createData.data && <span color='green'>Saved.</span>}
      {createData.error && (
        <span color='red'>Error saving: {createData.error.message}</span>
      )}
    </form>
  )
}

export default EditTraining
