'use client'

import { useEffect, useState } from 'react'

export interface SuggestedValue {
  value: number
  justification: string
}

export interface RiskSuggestion {
  hazard_id: string
  contact_mode: string
  en62061: {
    severity: SuggestedValue
    frequency: SuggestedValue
    probability: SuggestedValue
    avoidance: SuggestedValue
    score: number
    level: string
    formula: string
  }
  fine_kinney: {
    probability: SuggestedValue
    exposure: SuggestedValue
    consequence: SuggestedValue
    score: number
    band: string
    action: string
    formula: string
  }
  note: string
}

export interface HazardLite {
  id: string
  name: string
  category: string
  scenario?: string
}

export function useRiskAssessment(projectId: string) {
  const [hazards, setHazards] = useState<HazardLite[]>([])
  const [suggestions, setSuggestions] = useState<Record<string, RiskSuggestion>>({})
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let cancelled = false
    async function load() {
      setLoading(true)
      try {
        const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/hazards`)
        const json = res.ok ? await res.json() : {}
        const hz: HazardLite[] = json.hazards || json || []
        if (cancelled) return
        setHazards(hz)
        const entries = await Promise.all(
          hz.map(async (h) => {
            try {
              const r = await fetch(
                `/api/sdk/v1/iace/projects/${projectId}/hazards/${h.id}/risk-suggestion`,
              )
              return r.ok ? ([h.id, (await r.json()) as RiskSuggestion] as const) : null
            } catch {
              return null
            }
          }),
        )
        if (cancelled) return
        const map: Record<string, RiskSuggestion> = {}
        for (const e of entries) if (e) map[e[0]] = e[1]
        setSuggestions(map)
      } catch (err) {
        console.error('Failed to load risk assessment:', err)
      } finally {
        if (!cancelled) setLoading(false)
      }
    }
    load()
    return () => {
      cancelled = true
    }
  }, [projectId])

  return { hazards, suggestions, loading }
}
