import { Video, useCreateVideoMutation, useUpdateVideoMutation } from '../../gql'
import { TextInput, useForm } from '../../form'
import FileSelector from './FileSelector'
import { useRouter } from 'next/router'
import { prepareDataForDB } from '../../training/utils'

export interface IEditVideo {
  video?: Partial<Video>
}

const EditVideo = ({ video }: IEditVideo) => {
  const { values, onChange } = useForm(video ?? {})
  const [createVideo, createData] = useCreateVideoMutation()
  const [updateVideo, updateData] = useUpdateVideoMutation()
  const router = useRouter()

  return (
    <form
      onSubmit={async (event) => {
        event.preventDefault()
        const data = prepareDataForDB(values, video)
        console.log(data, video)
        if (video) {
          const { id, ...others } = data
          updateVideo({ variables: { data: others, where: { id: video.id } } })
        } else {
          const createResult = await createVideo({ variables: { data } })
          if (createResult) {
            router.push(`/admin/video/[id]`, `/admin/video/${createResult.data?.createVideo.id}`)
          }
        }
      }}
    >
      <TextInput name='title' label='Title' value={values.title} onChange={onChange} />
      <TextInput
        name='description'
        label='Description'
        value={values.description}
        onChange={onChange}
      />
      <TextInput
        name='duration'
        label='Duration'
        value={values.duration}
        type='number'
        onChange={onChange}
      />
      <FileSelector
        name='file'
        value={values.file}
        onChange={onChange}
        queryConf={{ where: { mimetype_starts_with: 'video/' } }}
      />
      {values.file?.thumbnail && <img src={`/${values.file.thumbnail}`} alt={values.title} />}
      <TextInput name='link' label='Link' value={values.link} onChange={onChange} />
      <button type='submit'>Save video</button>
    </form>
  )
}

export default EditVideo
