import { useCreateTrainingMutation, useUpdateTrainingMutation } from '../../gql'
import { useForm, TextInput, DateTimeInput, Checkbox } from '../../form'
import { emptyTraining, emptyBlockInstance, prepareDataForDB } from '../utils'
import TrainingTypeSelector from './TrainingTypeSelector'
import BlockInstanceInputs from './BlockInstanceInputs'
import { TTraining } from '../types'
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={async (event) => {
        event.preventDefault()
        const newValues = prepareDataForDB(values, training || emptyTraining())
        if (!newValues || Object.keys(newValues).length === 0) {
          console.log('no changes.')
          return
        }
        console.log(newValues)
        const { id, ...data } = newValues
        if (id.startsWith('++')) {
          const createData = await createTraining({ variables: data })
          console.log('created training', createData)
        } else if (id.startsWith('@@')) {
          const updateData = await updateTraining({
            variables: { where: { id: id.substr(2) }, data },
          })
          console.log('updated training', updateData)
        }
      }}
    >
      <fieldset className='fields-training'>
        <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>}
      </fieldset>

      <style jsx>{`
        .fields-training {
          display: grid;
        }
      `}</style>
    </form>
  )
}

export default EditTraining
