import { notify } from '@inject/shared/notification/engine'
import { useCallback, useEffect, useState } from 'react'
import { fetchBranches } from '../gitlabAccess'
import type { GitlabConfig } from '../useGitlabStorage'
import useGitlabStorage from '../useGitlabStorage'

const useBranches = (projectId?: string) => {
  const [branches, setBranches] = useState<string[]>([])

  const [gitlabConfig] = useGitlabStorage()

  const fetchData = useCallback(async (conf: GitlabConfig, id: string) => {
    try {
      const result = await fetchBranches(conf, id)
      setBranches(result.length ? result.map(branch => branch.name) : ['main'])
    } catch (error) {
      notify((error as Error).message, { intent: 'danger' })
    }
  }, [])

  useEffect(() => {
    if (!gitlabConfig || !projectId) return

    fetchData(gitlabConfig, projectId)
  }, [gitlabConfig, projectId])

  return branches
}

export default useBranches
