'use client'

import { useState, useEffect } from 'react'

export interface MonitoringEvent {
  id: string
  event_type: 'incident' | 'update' | 'drift_alert' | 'regulation_change'
  title: string
  description: string
  severity: 'low' | 'medium' | 'high' | 'critical'
  status: 'open' | 'investigating' | 'resolved' | 'closed'
  created_at: string
  resolved_at: string | null
  resolved_by: string | null
  resolution_notes: string | null
}

export interface EventFormData {
  event_type: string
  title: string
  description: string
  severity: string
}

export function useMonitoring(projectId: string) {
  const [events, setEvents] = useState<MonitoringEvent[]>([])
  const [loading, setLoading] = useState(true)
  const [showForm, setShowForm] = useState(false)
  const [resolvingEvent, setResolvingEvent] = useState<MonitoringEvent | null>(null)
  const [filterType, setFilterType] = useState('')
  const [filterStatus, setFilterStatus] = useState('')

  useEffect(() => {
    fetchEvents()
  }, [projectId])

  async function fetchEvents() {
    try {
      const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/monitoring`)
      if (res.ok) {
        const json = await res.json()
        setEvents(json.events || json || [])
      }
    } catch (err) {
      console.error('Failed to fetch monitoring events:', err)
    } finally {
      setLoading(false)
    }
  }

  async function handleSubmit(data: EventFormData) {
    try {
      const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/monitoring`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      })
      if (res.ok) {
        setShowForm(false)
        await fetchEvents()
      }
    } catch (err) {
      console.error('Failed to add event:', err)
    }
  }

  async function handleResolve(id: string, notes: string) {
    try {
      const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/monitoring/${id}/resolve`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ resolution_notes: notes }),
      })
      if (res.ok) {
        setResolvingEvent(null)
        await fetchEvents()
      }
    } catch (err) {
      console.error('Failed to resolve event:', err)
    }
  }

  const filteredEvents = events.filter((e) => {
    const matchType = !filterType || e.event_type === filterType
    const matchStatus = !filterStatus || e.status === filterStatus
    return matchType && matchStatus
  })

  const openCount = events.filter((e) => e.status === 'open' || e.status === 'investigating').length
  const resolvedCount = events.filter((e) => e.status === 'resolved' || e.status === 'closed').length

  return {
    events, loading, showForm, resolvingEvent,
    filterType, filterStatus, filteredEvents,
    openCount, resolvedCount,
    setShowForm, setResolvingEvent, setFilterType, setFilterStatus,
    handleSubmit, handleResolve,
  }
}
