import type { Path } from '@/router'
import { useNavigate } from '@/router'
import type { ButtonProps } from '@blueprintjs/core'
import {
  Button,
  ButtonGroup,
  Dialog,
  DialogBody,
  DialogFooter,
} from '@blueprintjs/core'
import { memo, useCallback, useState, type FC } from 'react'
import { DATA_REMOVAL_CONTENT } from '../assets/dialogContent'
import { GENERIC_CONTENT } from '../assets/generalContent'
import { clearDb } from '../indexeddb/operations'
import useEditorAccessStorage from '../useEditorAccessStorage'
import useEditorStorage from '../useEditorStorage'
import useGitlabStorage from '../useGitlabStorage'

interface DataRemovalDialogProps {
  openButtonProps: ButtonProps
  confirmButtonProps: ButtonProps
  redirectTo: Path
}

const DataRemovalDialog: FC<DataRemovalDialogProps> = ({
  openButtonProps,
  confirmButtonProps,
  redirectTo,
}) => {
  const [isOpen, setIsOpen] = useState(false)
  const [, setAccess] = useEditorAccessStorage()
  const [, setConfig] = useEditorStorage()
  const [, setGitlab] = useGitlabStorage()
  const nav = useNavigate()

  const handleConfirmButton = useCallback(async () => {
    clearDb()
    setConfig({})
    setAccess({})
    setGitlab(prev => ({ ...prev, project: undefined, branchFrom: undefined }))
    nav(redirectTo)
  }, [redirectTo])

  return (
    <>
      <Button {...openButtonProps} onClick={() => setIsOpen(true)} />
      <Dialog
        isOpen={isOpen}
        onClose={() => setIsOpen(false)}
        icon='warning-sign'
        title='Clear definition'
      >
        <DialogBody>
          <p>{DATA_REMOVAL_CONTENT}</p>
        </DialogBody>
        <DialogFooter
          actions={
            <ButtonGroup>
              <Button
                onClick={() => setIsOpen(false)}
                icon='cross'
                text={GENERIC_CONTENT.buttons.cancel}
              />
              <Button
                onClick={() => handleConfirmButton()}
                {...confirmButtonProps}
              />
            </ButtonGroup>
          }
        />
      </Dialog>
    </>
  )
}

export default memo(DataRemovalDialog)
