import PropTypes from 'prop-types'
import ObjectInfo from '../../common/ObjectInfo'
import NewObjectForm from '../../common/NewObjectForm'
import WizardView from '../../common/WizardView'
import TemplatePreview from '../../common/TemplatePreview'
import { ApiServerContext } from '../../context/ApiServerContext'
import { useContext, useRef, useState } from 'react'
import dayjs from 'dayjs'

const NewDocumentJob = ({ onOk, defaultValues = {} }) => {
  const { sendObjectAction, downloadTemplatePDF, formatFileName } =
    useContext(ApiServerContext)
  const [downloading, setDownloading] = useState(false)

  // Capture initial default values so later prop changes don't re-initialize the form
  const defaultValuesRef = useRef({
    objectType: 'documentJob',
    ...defaultValues,
    saveToFile: false
  })

  return (
    <NewObjectForm
      type={'documentJob'}
      defaultValues={defaultValuesRef.current}
    >
      {({ handleSubmit, submitLoading, objectData, formValid }) => {
        const steps = [
          {
            title: 'Required',
            key: 'required',
            content: (
              <ObjectInfo
                type='documentJob'
                column={1}
                visibleProperties={{ name: false }}
                bordered={false}
                isEditing={true}
                required={true}
                objectData={objectData}
              />
            )
          }
        ]
        const fileName =
          formatFileName(
            objectData?.name + ' ' + dayjs().format('YYYY-MM-DD HH:mm:ss')
          ) || 'document'
        return (
          <WizardView
            steps={steps}
            submitText='Print'
            title={'Print Document'}
            formValid={formValid}
            loading={submitLoading}
            disabled={downloading}
            sideBarGrow={true}
            sideBar={
              <div style={{ minHeight: '500px', flexGrow: 1 }}>
                <TemplatePreview
                  objectData={objectData?.object}
                  documentTemplate={objectData?.documentTemplate}
                  onPreviewMessage={(message) => {
                    console.log(message)
                  }}
                />
              </div>
            }
            onSubmit={async () => {
              const newDocumentJob = await handleSubmit()
              if (newDocumentJob.sendToFile == true) {
                sendObjectAction(newDocumentJob._id, 'documentJob', {
                  type: 'print',
                  data: newDocumentJob
                })
              }
              if (onOk) {
                onOk()
              }
            }}
            actions={[
              {
                label: 'Download',
                steps: ['required'],
                loading: downloading == true,
                disabled: downloading == true || submitLoading == true,
                children: [
                  {
                    label: 'PDF',
                    key: 'pdf',
                    onClick: () => {
                      setDownloading(true)
                      downloadTemplatePDF(
                        objectData.documentTemplate._id,
                        objectData.documentTemplate.content,
                        objectData.object,
                        fileName,
                        () => {
                          setDownloading(false)
                        }
                      )
                    }
                  },
                  {
                    label: 'PNG',
                    key: 'png'
                  },
                  {
                    label: 'JPEG',
                    key: 'jpeg'
                  }
                ]
              }
            ]}
          />
        )
      }}
    </NewObjectForm>
  )
}

NewDocumentJob.propTypes = {
  onOk: PropTypes.func.isRequired,
  reset: PropTypes.bool,
  defaultValues: PropTypes.object
}

export default NewDocumentJob
