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}
                labelWidth={115}
                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: '760px', flexGrow: 1 }}>
                <TemplatePreview
                  objectData={objectData?.object}
                  documentTemplate={objectData?.documentTemplate}
                />
              </div>
            }
            onSubmit={async () => {
              const newDocumentJob = await handleSubmit()
              if (newDocumentJob) {
                await sendObjectAction(
                  newDocumentJob.documentPrinter._id,
                  'documentPrinter',
                  {
                    type: 'deploy',
                    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
