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'
import BlockList from './BlockList'
import theme from '../../styles/theme'

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'>
        {!values.id.startsWith('++') && (
          <div className='training-info'>
            <div>Training ID: {values.id}, </div>
            <div>Created at: {values.createdAt}</div>
          </div>
        )}
        <TextInput
          name='title'
          label='Title'
          value={values.title}
          onChange={onChange}
          className='training-title'
        />
        <TrainingTypeSelector
          name='type'
          value={values.type}
          onChange={onChange}
          className='training-type'
        />
        <DateTimeInput
          name='trainingDate'
          label='Training date'
          value={values.trainingDate}
          onChange={onChange}
          className='training-time'
        />
        <TextInput
          name='location'
          label='Location'
          value={values.location}
          onChange={onChange}
          className='training-location'
        />
        <Registrations registrations={values.registrations} className='training-registrations' />
        <TextInput
          name='attendance'
          label='Attendance'
          type='number'
          value={values.attendance}
          onChange={onChange}
          className='training-attendance'
        />
        <Ratings ratings={values.ratings} className='training-ratings' />
        <Checkbox
          name='published'
          label='Published'
          value={values.published}
          onChange={onChange}
          className='training-published'
        />
        <BlockList
          name='blocks'
          value={values.blocks}
          onChange={onChange}
          className='training-blocks'
        />
        <button type='submit' disabled={createData.loading} className='training-button'>
          Save Training
        </button>
        {createData.data && <span color='green'>Saved.</span>}
        {createData.error && <span color='red'>Error saving: {createData.error.message}</span>}
      </fieldset>

      <style jsx>{`
        .fields-training :global(.training-title) {
          font-size: 120%;
        }

        @media (min-width: ${theme.midsize}) {
          .fields-training {
            display: grid;
            grid-gap: 0.2em 2em;
            grid-template-areas:
              'info info info'
              'title title type'
              'time time location'
              'published attendance empty2'
              'registrations ratings empty3'
              'blocks blocks blocks'
              'button button button';
            grid-template-columns: 1fr 1fr 1fr;
            align-items: center;
          }
          .fields-training :global(.training-info) {
            grid-area: info;
            display: flex;
            justify-content: space-between;
          }
          .fields-training :global(.training-title) {
            grid-area: title;
            font-size: 140%;
          }
          .fields-training :global(.training-type) {
            grid-area: type;
          }
          .fields-training :global(.training-time) {
            grid-area: time;
          }
          .fields-training :global(.training-location) {
            grid-area: location;
          }
          .fields-training :global(.training-published) {
            grid-area: published;
          }
          .fields-training :global(.training-attendance) {
            grid-area: attendance;
          }
          .fields-training :global(.training-registrations) {
            grid-area: registrations;
          }
          .fields-training :global(.training-ratings) {
            grid-area: ratings;
          }
          .fields-training :global(.training-blocks) {
            grid-area: blocks;
          }
          .fields-training :global(.training-button) {
            grid-area: button;
          }
        }
      `}</style>
    </form>
  )
}

export default EditTraining
