import { useEffect, useState } from 'react'

import type { DependencyEdge, GiteaIssue, GiteaMilestone } from '@commitea/core'

export type BacklogState =
  | { status: 'loading' }
  | { status: 'unconfigured' }
  | { status: 'error'; message: string }
  | { status: 'ready'; issues: GiteaIssue[]; milestones: GiteaMilestone[]; deps: DependencyEdge[] }

/**
 * Reconcile the managed repo once on mount, through the main-process bridge.
 * `unconfigured` means no token — the UI falls back to demo fixtures. Errors
 * (network, bad token) surface as `error`.
 */
export function useBacklog(): BacklogState {
  const [state, setState] = useState<BacklogState>({ status: 'loading' })

  useEffect(() => {
    let alive = true
    window.commitea.gitea
      .reconcile()
      .then((r) => {
        if (!alive) return
        setState(
          r.configured
            ? { status: 'ready', issues: r.issues, milestones: r.milestones, deps: r.deps }
            : { status: 'unconfigured' },
        )
      })
      .catch((e: unknown) => {
        if (alive) setState({ status: 'error', message: e instanceof Error ? e.message : String(e) })
      })
    return () => {
      alive = false
    }
  }, [])

  return state
}
