import { useCreateTrainingMutation, useUpdateTrainingMutation } from '../../gql'
import { useForm, TextInput, DateTimeInput, Checkbox } from '../../form'
import { emptyTraining, prepareDataForDB } from '../utils'
import TrainingTypeSelector from './TrainingTypeSelector'
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, updateData] = useUpdateTrainingMutation()

  return (
    <form
      onSubmit={async (event) => {
        event.preventDefault()
        const newValues = prepareDataForDB(values, training || {})
        if (!newValues || Object.keys(newValues).length === 0) {
          console.log('no changes.')
          return
        }
        console.log(newValues)
        const { id, ...data } = newValues
        if (id?.startsWith('@@')) {
          const updateData = await updateTraining({
            variables: { where: { id: id.substr(2) }, data },
          })
          console.log('updated training', updateData)
        } else if (id.startsWith('@@')) {
          const createData = await createTraining({ variables: data })
          console.log('created training', createData)
        }
      }}
    >
      <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'
        />
        <Checkbox
          name='published'
          label='Published'
          value={values.published}
          onChange={onChange}
          className='training-published'
        />
        <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'
        />
        <TextInput
          name='attendance'
          label='Attendance'
          type='number'
          value={values.attendance}
          onChange={onChange}
          className='training-attendance'
        />
        <Registrations registrations={values.registrations} className='training-registrations' />
        <Ratings ratings={values.ratings} className='training-ratings' />
        <BlockList
          name='blocks'
          value={values.blocks}
          onChange={onChange}
          className='training-blocks'
        />
        <div className='training-button'>
          <button type='submit' disabled={createData.loading}>
            Save Training
          </button>
          {(createData.data || updateData.data) && <span color='green'>Saved.</span>}
          {(createData.error || updateData.error) && (
            <span color='red'>
              Error saving: {createData.error?.message ?? updateData.error?.message}
            </span>
          )}
        </div>
      </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 info'
              'title title type published'
              'time location location attendance'
              'registrations registrations ratings ratings'
              'blocks blocks blocks blocks'
              'button button button button';
            grid-template-columns: 1fr 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
