import type { Project } from '@/editor/gitlabAccess'
import { fetchProjects, validateGitLabGroupToken } from '@/editor/gitlabAccess'
import { useNavigate } from '@/router'
import { CardList } from '@blueprintjs/core'
import { notify } from '@inject/shared/notification/engine'
import { memo, useCallback, useEffect, useState } from 'react'
import type { GitlabConfig } from '../useGitlabStorage'
import useGitlabStorage from '../useGitlabStorage'
import Definition from './Definition'

const Definitions = () => {
  const [config, setConfig] = useGitlabStorage()
  const [projects, setProjects] = useState<Project[]>([])
  const nav = useNavigate()

  const validateAndFetch = useCallback(async (config: GitlabConfig) => {
    const result = await validateGitLabGroupToken(config, config.token)
    if (!result) nav('/editor/gitlab-settings', { state: true })
    else {
      setConfig(prev => ({ ...prev, groupId: result }))
      fetchData(config)
    }
  }, [])

  useEffect(() => {
    if (!config) return
    validateAndFetch(config)
  }, [config])

  const fetchData = useCallback(async (conf: GitlabConfig) => {
    if (!conf) return
    try {
      const result = await fetchProjects(conf)
      setProjects(result)
    } catch (error) {
      notify((error as Error).message, { intent: 'danger' })
    }
  }, [])

  return (
    <CardList>
      {projects.map(project => (
        <Definition project={project} key={project.id} />
      ))}
    </CardList>
  )
}

export default memo(Definitions)
