'use client'

/**
 * Demo Page - 戰情室
 * ==================
 * Phase 1: 視覺靈魂注入 - Lab-White Style
 *
 * - NemoClaw 3D 陶瓷機械爪視覺化
 * - VT323 點陣字體品牌識別
 * - LiveDashboard: SSE 串流真實主機數據
 * - HITLSection: AI 思考流 → 動態卡片對接
 */

import { useCallback, useMemo, useState } from 'react'
import { useTranslations } from 'next-intl'
import { AppLayout } from '@/components/layout'
import { LiveDashboard } from '@/components/dashboard/live-dashboard'
import { HITLSection } from '@/components/ai'

// =============================================================================
// API Configuration (專案鐵律: 禁止任何 Fallback IP)
// =============================================================================

const getApiBaseUrl = (): string => {
  if (typeof window === 'undefined') return ''
  const url = process.env.NEXT_PUBLIC_API_URL
  if (!url) {
    console.error('[AWOOOI ERROR] Missing NEXT_PUBLIC_API_URL') // eslint-disable-line no-console
    return ''
  }
  return url
}

const API_BASE_URL = getApiBaseUrl()

// =============================================================================
// Create Test Approval (i18n aware)
// =============================================================================

interface CreateApprovalConfig {
  action: string
  description: string
  data_impact: string
  rbacLabel: string
  syntaxLabel: string
  backupLabel: string
  backupMessage: string
  okMessage: string
}

async function createTestApprovalWithConfig(
  riskLevel: 'low' | 'medium' | 'critical',
  config: CreateApprovalConfig
) {
  const response = await fetch(`${API_BASE_URL}/api/v1/approvals`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      action: config.action,
      description: config.description,
      risk_level: riskLevel,
      blast_radius: {
        affected_pods: riskLevel === 'critical' ? 0 : 3,
        estimated_downtime: riskLevel === 'low' ? '0' : '~2 min',
        related_services: ['auth-service', 'api-gateway', 'user-service'],
        data_impact: config.data_impact,
      },
      dry_run_checks: [
        { name: config.rbacLabel, passed: true, message: 'cluster-admin' },
        { name: config.syntaxLabel, passed: true },
        { name: config.backupLabel, passed: riskLevel !== 'critical', message: riskLevel === 'critical' ? config.backupMessage : config.okMessage },
      ],
      requested_by: 'OpenClaw',
    }),
  })

  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`)
  }

  return response.json()
}

// =============================================================================
// Main Demo Page
// =============================================================================

export default function DemoPage({ params }: { params: { locale: string } }) {
  const t = useTranslations('demo')
  const tBrand = useTranslations('brand')
  const tApproval = useTranslations('approval')
  const tMock = useTranslations('mockData')
  const tDryRun = useTranslations('dryRun')
  const locale = params.locale

  // 生產環境保護: 需要 NEXT_PUBLIC_ENABLE_DEMO=true 才能存取
  if (process.env.NEXT_PUBLIC_ENABLE_DEMO !== 'true') {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <p className="text-muted-foreground">展示頁已在正式環境停用。</p>
      </div>
    )
  }

  const [_isCreating, setIsCreating] = useState(false)
  const [createError, setCreateError] = useState<string | null>(null)

  // i18n-aware approval creation configs (memoized to prevent re-render dependency issues)
  const approvalConfigs = useMemo(() => ({
    low: {
      action: tMock('testActions.lowAction'),
      description: tMock('testActions.lowDesc'),
      data_impact: 'none',
      rbacLabel: tDryRun('rbac'),
      syntaxLabel: tDryRun('syntax'),
      backupLabel: tDryRun('backupAvailable'),
      backupMessage: tDryRun('noRecentBackup'),
      okMessage: tDryRun('ok'),
    },
    medium: {
      action: tMock('testActions.mediumAction'),
      description: tMock('testActions.mediumDesc'),
      data_impact: 'none',
      rbacLabel: tDryRun('rbac'),
      syntaxLabel: tDryRun('syntax'),
      backupLabel: tDryRun('backupAvailable'),
      backupMessage: tDryRun('noRecentBackup'),
      okMessage: tDryRun('ok'),
    },
    critical: {
      action: tMock('testActions.criticalAction'),
      description: tMock('testActions.criticalDesc'),
      data_impact: 'destructive',
      rbacLabel: tDryRun('rbac'),
      syntaxLabel: tDryRun('syntax'),
      backupLabel: tDryRun('backupAvailable'),
      backupMessage: tDryRun('noRecentBackup'),
      okMessage: tDryRun('ok'),
    },
  }), [tMock, tDryRun])

  const _handleCreateApproval = useCallback(async (riskLevel: 'low' | 'medium' | 'critical') => {
    setIsCreating(true)
    setCreateError(null)
    try {
      const result = await createTestApprovalWithConfig(riskLevel, approvalConfigs[riskLevel])
      console.log('[Demo] Created approval:', result) // eslint-disable-line no-console
    } catch (err) {
      setCreateError(`${tApproval('fetchError')}: ${err}`)
      console.error('[Demo] Create approval failed:', err) // eslint-disable-line no-console
    } finally {
      setIsCreating(false)
    }
  }, [approvalConfigs, tApproval])

  return (
    <AppLayout locale={locale}>
      <div className="max-w-7xl mx-auto space-y-8">
        {/* Page Title - Dot Matrix Style */}
        <header className="text-center py-6">
          <h1 className="font-dot-matrix text-4xl text-nothing-gray-800 tracking-wider mb-2">
            AWOOOI
          </h1>
          <p className="font-dot-matrix text-lg text-claw-blue">
            {tBrand('aiTagline')}
          </p>
        </header>

        {/* Live Dashboard - Real SSE Data */}
        <section>
          <h2 className="font-dot-matrix text-2xl text-nothing-gray-700 mb-4 tracking-wide">
            {t('liveDashboard')}
          </h2>
          <LiveDashboard locale={locale} />
        </section>

        {/* HITL Section - NemoClaw + Approval Cards */}
        <HITLSection locale={locale} />

        {/* Error Display */}
        {createError && (
          <div className="p-3 bg-status-critical/10 border border-status-critical/30 rounded-lg">
            <p className="text-sm text-status-critical font-body">{createError}</p>
          </div>
        )}
      </div>
    </AppLayout>
  )
}
