'use client'
import { useState, useEffect, useRef } from 'react'
import { getIngestionStatus } from '@/lib/services'
import type { IngestionJobStatus } from '@/types'

const TERMINAL_STATES = new Set<IngestionJobStatus['status']>(['done', 'failed'])
const POLL_INTERVAL_MS = 3000

interface UseIngestionStatusResult {
  status: IngestionJobStatus | null
  progress: number
  error: string | null
}

function calcProgress(s: IngestionJobStatus): number {
  const stageMap: Record<IngestionJobStatus['status'], number> = {
    queued: 5,
    extracting: 15,
    chunking: 30,
    structuring: 50,
    writing: 65,
    embedding:
      s.chunksTotal > 0 ? 65 + Math.round((s.chunksEmbedded / s.chunksTotal) * 30) : 70,
    done: 100,
    failed: 0,
  }
  return stageMap[s.status] ?? 0
}

export function useIngestionStatus(jobId: string | null): UseIngestionStatusResult {
  const [status, setStatus] = useState<IngestionJobStatus | null>(null)
  const [error, setError] = useState<string | null>(null)
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null)

  useEffect(() => {
    if (!jobId) return

    let cancelled = false

    async function poll() {
      if (cancelled) return
      try {
        const result = await getIngestionStatus(jobId!)
        if (cancelled) return
        setStatus(result)
        setError(null)
        if (!TERMINAL_STATES.has(result.status)) {
          timerRef.current = setTimeout(poll, POLL_INTERVAL_MS)
        }
      } catch (err) {
        if (cancelled) return
        setError(err instanceof Error ? err.message : 'Unknown error')
      }
    }

    void poll()

    return () => {
      cancelled = true
      if (timerRef.current) clearTimeout(timerRef.current)
    }
  }, [jobId])

  return {
    status,
    progress: status ? calcProgress(status) : 0,
    error,
  }
}
