import { notify } from '@inject/shared/notification/engine'
import type { FC } from 'react'
import { memo, useCallback, useEffect, useState } from 'react'
import BranchSelector from '../BranchSelector'
import useBranches from '../BranchSelector/useBranches'
import DefinitionImportDialog from '../DefinitionImportDialog'
import TooltipLabel from '../Tooltips/TooltipLabel'
import { COMMIT_FORM } from '../assets/pageContent/gitlab'
import type { Project } from '../gitlabAccess'
import { downloadDefinition } from '../gitlabAccess'
import type { GitlabConfig } from '../useGitlabStorage'
import useGitlabStorage from '../useGitlabStorage'

interface BranchSelectorDialogProps {
  project: Project
}

const BranchSelectorDialog: FC<BranchSelectorDialogProps> = ({ project }) => {
  const branches = useBranches(project.id)
  const [selectedBranch, setSelectedBranch] = useState<string>('')

  const [gitlabConfig, setGitlabConfig] = useGitlabStorage()

  useEffect(() => {
    if (!branches.length || branches.find(branch => branch === selectedBranch))
      return

    setSelectedBranch(branches[0])
  }, [branches, selectedBranch])

  const handleDownload = useCallback(
    async (branch: string) => {
      try {
        if (!gitlabConfig) return

        const definition = await downloadDefinition(
          gitlabConfig,
          project.id,
          branch
        )
        if (!definition) return

        const newConfig: GitlabConfig = {
          ...gitlabConfig,
          project: {
            id: project.id,
            name: project.name,
            description: project.description,
          },
          branchFrom: branch,
        }
        setGitlabConfig(newConfig)
        return { file: new File([definition], 'definition'), config: newConfig }
      } catch (error) {
        notify((error as Error).message, { intent: 'danger' })
      }
    },
    [gitlabConfig, project]
  )

  return (
    <DefinitionImportDialog
      openButtonProps={{ text: 'Select' }}
      addDisabled={!selectedBranch}
      onAdd={() => handleDownload(selectedBranch)}
    >
      <p>Project: {project.name}</p>
      <TooltipLabel label={COMMIT_FORM.branch}>
        <BranchSelector
          branches={branches}
          selectedBranch={selectedBranch}
          onSelectedBranchChange={value => setSelectedBranch(value)}
        />
      </TooltipLabel>
    </DefinitionImportDialog>
  )
}

export default memo(BranchSelectorDialog)
