'use client'

import { useState, useEffect } from 'react'

export interface AuditEntry {
  id: string
  entity_type: string
  entity_id: string
  entity_name: string
  action: string
  field_changed: string | null
  old_value: string | null
  new_value: string | null
  change_summary: string | null
  performed_by: string
  performed_at: string
}

export function useAuditTimeline() {
  const [entries, setEntries] = useState<AuditEntry[]>([])
  const [loading, setLoading] = useState(true)
  const [filter, setFilter] = useState<string>('all')

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

  async function loadEntries() {
    setLoading(true)
    try {
      const params = new URLSearchParams({ limit: '100' })
      if (filter !== 'all') params.set('entity_type', filter)
      const res = await fetch(`/api/sdk/v1/compliance/audit-trail?${params}`)
      if (res.ok) {
        const json = await res.json()
        setEntries(json.entries || json.audit_trail || json || [])
      }
    } catch (err) {
      console.error('Failed to load audit trail:', err)
    } finally {
      setLoading(false)
    }
  }

  return { entries, loading, filter, setFilter }
}
