'use client'

import { useState, useEffect } from 'react'
import { Escalation, EscalationStats } from '../_components/types'

export function useEscalations(filter: string) {
  const [escalations, setEscalations] = useState<Escalation[]>([])
  const [stats, setStats] = useState<EscalationStats | null>(null)
  const [loading, setLoading] = useState(true)

  async function loadEscalations() {
    try {
      const params = new URLSearchParams({ limit: '100' })
      if (filter !== 'all' && ['open', 'in_progress', 'escalated', 'resolved', 'closed'].includes(filter)) {
        params.set('status', filter)
      } else if (filter !== 'all' && ['low', 'medium', 'high', 'critical'].includes(filter)) {
        params.set('priority', filter)
      }
      const res = await fetch(`/api/sdk/v1/escalations?${params}`)
      if (res.ok) {
        const data = await res.json()
        setEscalations(data.items || [])
      }
    } catch (e) {
      console.error('Failed to load escalations', e)
    }
  }

  async function loadStats() {
    try {
      const res = await fetch('/api/sdk/v1/escalations/stats')
      if (res.ok) {
        const data = await res.json()
        setStats(data)
      }
    } catch (e) {
      console.error('Failed to load stats', e)
    }
  }

  async function loadAll() {
    setLoading(true)
    await Promise.all([loadEscalations(), loadStats()])
    setLoading(false)
  }

  useEffect(() => {
    loadAll()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filter])

  return { escalations, stats, loading, loadAll }
}
