'use client'

/**
 * Authorizations Page - 授權中心
 * ==============================
 * HITL 即時授權頁面，整合 LiveApprovalPanel
 * 含 Multi-Sig、權限擋板、SSE 即時更新
 *
 * @updated 2026-04-01 ogt - 從佔位符升級為完整頁面
 * @updated 2026-05-31 Codex - 焦點 Incident 接上 status-chain / timeline / pending approval 真相鏈
 */

import { useEffect, useState } from 'react'
import { useSearchParams } from 'next/navigation'
import { useTranslations } from 'next-intl'

import { AppLayout } from '@/components/layout'
import { IncidentAuthorizationFocus } from '@/components/approval/incident-authorization-focus'
import { LiveApprovalPanel } from '@/components/approval/live-approval-panel'
import type { AwoooPStatusChain } from '@/components/awooop/status-chain'
import { IwoooSReadOnlyBridge } from '@/components/security/iwooos-read-only-bridge'
import type { IncidentTimelineResponse } from '@/lib/api-client'
import type { ApprovalRequest } from '@/stores/approval.store'

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

async function fetchJson<T>(url: string): Promise<T | null> {
  const response = await fetch(url)
  if (!response.ok) throw new Error(`HTTP ${response.status}`)
  return response.json()
}

function normalizePendingApprovals(payload: unknown): ApprovalRequest[] {
  if (Array.isArray(payload)) return payload as ApprovalRequest[]
  if (payload && typeof payload === 'object' && Array.isArray((payload as { approvals?: unknown }).approvals)) {
    return (payload as { approvals: ApprovalRequest[] }).approvals
  }
  return []
}

export default function AuthorizationsPage({
  params,
}: {
  params: { locale: string }
}) {
  const t = useTranslations('authorizations.incidentFocus')
  const searchParams = useSearchParams()
  const projectId = searchParams.get('project_id') ?? 'awoooi'
  const incidentId = searchParams.get('incident_id')
  const approvalId = searchParams.get('approval_id')
  const [chain, setChain] = useState<AwoooPStatusChain | null>(null)
  const [timeline, setTimeline] = useState<IncidentTimelineResponse | null>(null)
  const [pendingApprovals, setPendingApprovals] = useState<ApprovalRequest[]>([])
  const [focusLoading, setFocusLoading] = useState(false)
  const [focusError, setFocusError] = useState<string | null>(null)

  useEffect(() => {
    let cancelled = false
    if (!incidentId) {
      setChain(null)
      setTimeline(null)
      setPendingApprovals([])
      setFocusError(null)
      setFocusLoading(false)
      return () => {
        cancelled = true
      }
    }
    const focusedIncidentId = incidentId

    async function loadFocus() {
      setFocusLoading(true)
      setFocusError(null)
      const encodedProjectId = encodeURIComponent(projectId)
      const encodedIncidentId = encodeURIComponent(focusedIncidentId)
      const [statusChainResult, timelineResult, pendingResult] = await Promise.allSettled([
        fetchJson<AwoooPStatusChain>(
          `${API_BASE}/api/v1/platform/status-chain?project_id=${encodedProjectId}&incident_id=${encodedIncidentId}`
        ),
        fetchJson<IncidentTimelineResponse>(`${API_BASE}/api/v1/incidents/${encodedIncidentId}/timeline`),
        fetchJson<unknown>(`${API_BASE}/api/v1/approvals/pending`),
      ])

      if (cancelled) return

      const nextChain = statusChainResult.status === 'fulfilled' ? statusChainResult.value : null
      const nextTimeline = timelineResult.status === 'fulfilled' ? timelineResult.value : null
      const nextPending = pendingResult.status === 'fulfilled' ? normalizePendingApprovals(pendingResult.value) : []
      setChain(nextChain)
      setTimeline(nextTimeline)
      setPendingApprovals(nextPending)

      const failures = [
        statusChainResult.status === 'rejected' ? t('statusChainLoadFailed') : null,
        timelineResult.status === 'rejected' ? t('timelineLoadFailed') : null,
        pendingResult.status === 'rejected' ? t('pendingLoadFailed') : null,
      ].filter(Boolean)
      setFocusError(failures.length > 0 ? failures.join(' / ') : null)
      setFocusLoading(false)
    }

    loadFocus()
    return () => {
      cancelled = true
    }
  }, [incidentId, projectId, t])

  return (
    <AppLayout locale={params.locale}>
      <div className="space-y-4">
        {incidentId ? (
          <IncidentAuthorizationFocus
            projectId={projectId}
            incidentId={incidentId}
            approvalId={approvalId}
            chain={chain}
            timeline={timeline}
            pendingApprovals={pendingApprovals}
            loading={focusLoading}
            error={focusError}
          />
        ) : null}
        <IwoooSReadOnlyBridge />
        <LiveApprovalPanel />
      </div>
    </AppLayout>
  )
}
