import { Button, ButtonGroup, Divider, MenuItem } from '@blueprintjs/core'
import { Select } from '@blueprintjs/select'
import type { FC } from 'react'
import { useState } from 'react'
import { saveSvgAsPng } from 'save-svg-as-png'

const getSnapshotFilename = () => {
  const now = new Date()
  return `inject-overview-${now.toISOString()}`
}

const downloadSVG = (elementId: string) => {
  const svgElement = document.getElementById(elementId)
  if (!svgElement) throw new Error(`element with id ${elementId} not found`)
  const svgString = new XMLSerializer().serializeToString(svgElement)
  const dataURL = `data:image/svg+xml;base64,${btoa(svgString)}`
  const downloadLink = document.createElement('a')
  downloadLink.href = dataURL
  downloadLink.download = `${getSnapshotFilename()}.svg`
  downloadLink.click()
}

const downloadPNG = (elementId: string) => {
  const svgElement = document.getElementById(elementId)
  if (!svgElement) throw new Error(`element with id ${elementId} not found`)
  saveSvgAsPng(svgElement, `${getSnapshotFilename()}.png`)
}

interface DownloadSnapshotProps {
  elementId: string
}

const DownloadSnapshot: FC<DownloadSnapshotProps> = ({ elementId }) => {
  const [format, setFormat] = useState('.png')

  return (
    <ButtonGroup minimal>
      <Button
        onClick={() => {
          // eslint-disable-next-line @typescript-eslint/no-unused-expressions
          format === '.png' ? downloadPNG(elementId) : downloadSVG(elementId)
        }}
      >
        Download snapshot
      </Button>
      <Divider />
      <Select<'.png' | '.svg'>
        fill
        onItemSelect={format => setFormat(format)}
        items={['.png', '.svg']}
        popoverProps={{ minimal: true }}
        itemRenderer={(item, { handleClick }) => (
          <MenuItem
            key={item}
            onClick={handleClick}
            text={item}
            active={item === format}
          />
        )}
        filterable={false}
      >
        <Button
          alignText='left'
          fill
          rightIcon='double-caret-vertical'
          text={format}
        />
      </Select>
    </ButtonGroup>
  )
}

export default DownloadSnapshot
