import { useEffect, useState } from 'react'
import { activityRepo, resourceRepo, simulationRepo } from '@/persistence/repositories'
import { supabaseProcessRepo } from '@/persistence/supabase/process-repo'
import type { Process, Activity, Resource, Simulation } from '@/domain/types'

interface ReportData {
  process: Process | null
  simulation: Simulation | null
  activities: Activity[]
  resources: Resource[]
  isLoading: boolean
  error: string | null
}

export function useReportData(processId: string): ReportData {
  const [process, setProcess] = useState<Process | null>(null)
  const [simulation, setSimulation] = useState<Simulation | null>(null)
  const [activities, setActivities] = useState<Activity[]>([])
  const [resources, setResources] = useState<Resource[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    let cancelled = false

    async function load() {
      setIsLoading(true)
      setError(null)
      try {
        const [proc, sim, acts, res] = await Promise.all([
          supabaseProcessRepo.getById(processId),
          simulationRepo.getLatestByProcess(processId),
          activityRepo.getByProcess(processId),
          resourceRepo.getByProcess(processId),
        ])
        if (cancelled) return
        if (!proc) throw new Error('Proceso no encontrado en la base de datos local')
        if (!sim) throw new Error('Sin simulación disponible. Volvé al workspace y ejecutá "Simular" primero.')
        setProcess(proc)
        setSimulation(sim)
        setActivities(acts)
        setResources(res)
      } catch (err) {
        if (!cancelled) setError(err instanceof Error ? err.message : 'Error al cargar el reporte')
      } finally {
        if (!cancelled) setIsLoading(false)
      }
    }

    load()
    return () => { cancelled = true }
  }, [processId])

  return { process, simulation, activities, resources, isLoading, error }
}
