import { Button, ButtonGroup, Section } from '@blueprintjs/core'
import { useHost } from '@inject/graphql/connection/host'
import { exportImportUrl } from '@inject/shared/config'
import { notify } from '@inject/shared/notification/engine'
import authenticatedFetch from '@inject/shared/utils/authenticatedFetch'
import { useState } from 'react'
import ImportDialog from './ImportDialog'

const ExportImport = () => {
  const host = useHost()
  const [isImportOpen, setIsImportOpen] = useState(false)
  const [exportLoading, setExportLoading] = useState(false)

  const handleExport = () => {
    setExportLoading(true)
    authenticatedFetch(exportImportUrl(host || ''))
      .then(response => response.blob())
      .then(blob => {
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `IXP-export-${new Date().toISOString().substring(0, 18)}.zip`
        a.click()
      })
      .catch(error =>
        notify(error.message, JSON.stringify(error), { intent: 'danger' })
      )
      .finally(() => setExportLoading(false))
  }

  return (
    <>
      <Section
        title='Export and import'
        subtitle={
          <span>
            Exported data include <b>all definitions, exercises, and users</b>
          </span>
        }
        rightElement={
          <ButtonGroup>
            <Button
              icon='export'
              loading={exportLoading}
              onClick={handleExport}
            >
              Export
            </Button>
            <Button
              active={isImportOpen}
              onClick={() => setIsImportOpen(true)}
              icon='import'
            >
              Import
            </Button>
          </ButtonGroup>
        }
      />

      <ImportDialog
        isOpen={isImportOpen}
        onClose={() => setIsImportOpen(false)}
      />
    </>
  )
}

export default ExportImport
