import { Classes, FileInput } from '@blueprintjs/core'
import type { ChangeEvent } from 'react'
import { memo, useCallback, useState } from 'react'
import DefinitionImportDialog from '../DefinitionImportDialog'
import TooltipLabel from '../Tooltips/TooltipLabel'
import {
  DEFINITION_UPLOAD_FORM,
  LANDING_PAGE_ACTIONS,
} from '../assets/pageContent/landingPage'
import useGitlabStorage from '../useGitlabStorage'

const DefinitionUploader = () => {
  const [, setGitlabConfig] = useGitlabStorage()
  const [file, setFile] = useState<File | undefined>()

  const handleFileChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      setFile(e.target.files[0])
    }
  }, [])

  const handleAdd = useCallback(async (file?: File) => {
    setGitlabConfig(prev => ({
      ...prev,
      project: undefined,
      branchFrom: undefined,
    }))
    return { file }
  }, [])

  return (
    <DefinitionImportDialog
      openButtonProps={{ text: LANDING_PAGE_ACTIONS.upload, icon: 'import' }}
      addDisabled={!file}
      onAdd={() => handleAdd(file)}
    >
      <TooltipLabel label={DEFINITION_UPLOAD_FORM.file}>
        <FileInput
          className={Classes.INPUT}
          fill
          hasSelection={file !== undefined}
          text={file ? file.name : 'Choose file...'}
          onInputChange={handleFileChange}
        />
      </TooltipLabel>
    </DefinitionImportDialog>
  )
}

export default memo(DefinitionUploader)
