'use client'

/**
 * EventsTab — 治理事件日誌 Tab
 * ==============================
 * 消費：GET /api/v1/ai/governance/events（含 query params）
 *
 * 內容：
 *   1. EventsFilterBar — 篩選列
 *   2. EventsTable — 表格 + 展開行 + 分頁
 *
 * @updated 2026-05-02 Claude Sonnet 4.6 — governance PR 3-5 填入真實內容
 */

import { useEffect, useState, useCallback } from 'react'
import { EventsFilterBar, type EventsFilter } from '@/components/governance/events-filter-bar'
import { EventsTable, type GovernanceEvent } from '@/components/governance/events-table'

// =============================================================================
// Config
// =============================================================================

const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? ''
const PAGE_SIZE = 20

// =============================================================================
// API response type
// =============================================================================

interface EventsApiResponse {
  items?: GovernanceEvent[]
  total?: number
  page?: number
  page_size?: number
  event_types?: string[]
}

// =============================================================================
// Helpers
// =============================================================================

function buildQueryString(filter: EventsFilter, page: number): string {
  const params = new URLSearchParams()
  params.set('page', String(page))
  params.set('page_size', String(PAGE_SIZE))
  if (filter.eventTypes.length > 0) {
    filter.eventTypes.forEach(t => params.append('event_type', t))
  }
  if (filter.status !== 'all') params.set('status', filter.status)
  if (filter.severity !== 'all') params.set('severity', filter.severity)
  if (filter.dateFrom) params.set('date_from', filter.dateFrom)
  if (filter.dateTo) params.set('date_to', filter.dateTo)
  return params.toString()
}

// =============================================================================
// Component
// =============================================================================

const DEFAULT_FILTER: EventsFilter = {
  eventTypes: [],
  status: 'all',
  severity: 'all',
  dateFrom: '',
  dateTo: '',
}

export function EventsTab() {
  const [filter, setFilter] = useState<EventsFilter>(DEFAULT_FILTER)
  const [page, setPage] = useState(1)
  const [events, setEvents] = useState<GovernanceEvent[]>([])
  const [total, setTotal] = useState(0)
  const [availableEventTypes, setAvailableEventTypes] = useState<string[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(false)

  const fetchEvents = useCallback(() => {
    setLoading(true)
    const qs = buildQueryString(filter, page)
    fetch(`${API_BASE}/api/v1/ai/governance/events?${qs}`)
      .then(r => r.ok ? r.json() : Promise.reject(r.status))
      .then((d: EventsApiResponse) => {
        setEvents(d.items ?? [])
        setTotal(d.total ?? 0)
        if (d.event_types && d.event_types.length > 0) {
          setAvailableEventTypes(d.event_types)
        }
        setError(false)
      })
      .catch(() => setError(true))
      .finally(() => setLoading(false))
  }, [filter, page])

  // Re-fetch when filter or page changes
  useEffect(() => {
    fetchEvents()
  }, [fetchEvents])

  // Reset page when filter changes
  const handleFilterChange = (newFilter: EventsFilter) => {
    setFilter(newFilter)
    setPage(1)
  }

  return (
    <div style={{ padding: '16px 20px', display: 'flex', flexDirection: 'column', gap: 12 }}>

      {/* Filter bar */}
      <EventsFilterBar
        filter={filter}
        onChange={handleFilterChange}
        availableEventTypes={availableEventTypes}
      />

      {/* Table */}
      <div style={{
        background: '#fff',
        border: '0.5px solid #e0ddd4',
        borderRadius: 12,
        overflow: 'hidden',
        boxShadow: '0 2px 12px rgba(0,0,0,0.04)',
      }}>
        <EventsTable
          events={events}
          loading={loading}
          error={error}
          onRetry={fetchEvents}
          total={total}
          page={page}
          pageSize={PAGE_SIZE}
          onPageChange={setPage}
        />
      </div>
    </div>
  )
}
