'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, useRef } from 'react'
import { useSearchParams } from 'next/navigation'
import { EventsFilterBar, type EventsFilter } from '@/components/governance/events-filter-bar'
import {
  EventsTable,
  type DispatchRecord,
  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 GovernanceEventApiItem {
  id: string
  event_type: string
  severity?: 'critical' | 'warning' | 'info'
  triggered_at: string
  resolved?: boolean
  resolved_at?: string | null
  status?: 'resolved' | 'unresolved'
  impact?: string
  impact_summary?: string
  details?: Record<string, unknown>
  raw_data?: Record<string, unknown>
  remediation?: string | null
  dispatch_ids?: string[]
  dispatch_records?: DispatchRecord[]
}

interface EventsApiResponse {
  items?: GovernanceEventApiItem[]
  total?: number
  page?: number
  size?: number
  event_types?: string[]
}

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

function buildQueryString(filter: EventsFilter, page: number): string {
  const params = new URLSearchParams()
  params.set('page', String(page))
  params.set('size', String(PAGE_SIZE))
  const eventId = filter.eventId.trim()
  if (eventId) params.append('event_id', eventId)
  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()
}

function toGovernanceEvent(item: GovernanceEventApiItem): GovernanceEvent {
  const resolved = item.status
    ? item.status === 'resolved'
    : Boolean(item.resolved)
  const dispatchRecords = item.dispatch_records
    ?? (item.dispatch_ids ?? []).map((dispatchId) => ({
      created_at: item.triggered_at,
      action: dispatchId,
      status: 'pending' as const,
    }))

  return {
    id: item.id,
    event_type: item.event_type,
    triggered_at: item.triggered_at,
    status: resolved ? 'resolved' : 'unresolved',
    severity: item.severity,
    impact_summary: item.impact_summary ?? item.impact,
    raw_data: item.raw_data ?? item.details,
    remediation: item.remediation ?? undefined,
    dispatch_records: dispatchRecords,
  }
}

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

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

export function EventsTab() {
  const searchParams = useSearchParams()
  const eventIdFromUrl = searchParams.get('event_id')?.trim() ?? ''
  const [filter, setFilter] = useState<EventsFilter>(() => ({
    ...DEFAULT_FILTER,
    eventId: eventIdFromUrl,
  }))
  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 requestSeq = useRef(0)

  const fetchEvents = useCallback(() => {
    const requestId = requestSeq.current + 1
    requestSeq.current = requestId
    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) => {
        if (requestId !== requestSeq.current) return
        setEvents((d.items ?? []).map(toGovernanceEvent))
        setTotal(d.total ?? 0)
        if (d.event_types && d.event_types.length > 0) {
          setAvailableEventTypes(d.event_types)
        }
        setError(false)
      })
      .catch(() => {
        if (requestId !== requestSeq.current) return
        setError(true)
      })
      .finally(() => {
        if (requestId !== requestSeq.current) return
        setLoading(false)
      })
  }, [filter, page])

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

  useEffect(() => {
    setFilter(current => {
      if (current.eventId === eventIdFromUrl) return current
      return { ...current, eventId: eventIdFromUrl }
    })
    setPage(1)
  }, [eventIdFromUrl])

  // 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>
  )
}
