import type { ButtonProps } from '@blueprintjs/core'
import { Button, ButtonGroup, Popover } from '@blueprintjs/core'
import { css } from '@emotion/css'
import { useHost } from '@inject/graphql/connection/host'
import { downloadLogUrl } from '@inject/shared/config'
import { notify } from '@inject/shared/notification/engine'
import authenticatedFetch from '@inject/shared/utils/authenticatedFetch'
import type { FC } from 'react'
import { useState } from 'react'

const content = css`
  padding: 0.5rem;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
`

interface DownloadLogsButtonProps {
  exerciseId: string
  buttonProps?: ButtonProps
}

const DownloadLogsButton: FC<DownloadLogsButtonProps> = ({
  exerciseId,
  buttonProps,
}) => {
  const host = useHost()

  const [standardLoading, setStandardLoading] = useState(false)
  const [anonymizedLoading, setAnonymizedLoading] = useState(false)
  const handleClick = (anonymize: boolean) => {
    switch (anonymize) {
      case false:
        setStandardLoading(true)
        break
      case true:
        setAnonymizedLoading(true)
        break
    }
    authenticatedFetch(downloadLogUrl(host, exerciseId, anonymize))
      .then(response => response.blob())
      .then(blob => {
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `IXP-exercise-${exerciseId}-logs${anonymize ? '-anonymized' : ''}.zip`
        a.click()
      })
      .catch(error =>
        notify(error.message, JSON.stringify(error), { intent: 'danger' })
      )
      .finally(() => {
        switch (anonymize) {
          case false:
            setStandardLoading(false)
            break
          case true:
            setAnonymizedLoading(false)
            break
        }
      })
  }

  return (
    <Popover
      content={
        <div className={content}>
          <div>Download logs:</div>
          <ButtonGroup vertical alignText='left'>
            <Button
              loading={standardLoading}
              icon='people'
              onClick={() => handleClick(false)}
            >
              Standard
            </Button>
            <Button
              loading={anonymizedLoading}
              icon='blocked-person'
              onClick={() => handleClick(true)}
            >
              Anonymized
            </Button>
          </ButtonGroup>
        </div>
      }
      placement='right'
    >
      <Button
        icon='download'
        rightIcon='caret-right'
        text='Download logs'
        {...buttonProps}
      />
    </Popover>
  )
}

export default DownloadLogsButton
