'use client'

/**
 * 操作稽核 Page — K8s 操作執行紀錄
 * @created 2026-04-01 ogt - 路由佔位
 * @updated 2026-04-03 Claude Code - 串接 /api/v1/audit-logs 真實數據
 */

import { useState, useEffect } from 'react'
import { useTranslations } from 'next-intl'
import { AppLayout } from '@/components/layout'

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

interface AuditStats {
  total_executions: number
  success_count: number
  failure_count: number
  success_rate: number
  avg_duration_ms: number | null
  last_24h_count: number
  by_operation_type: Record<string, number>
  by_namespace: Record<string, number>
}

interface AuditLog {
  id: string
  operation_type: string
  namespace: string | null
  success: boolean
  duration_ms: number | null
  created_at: string
  error_message: string | null
}

interface AuditLogListResponse {
  logs: AuditLog[]
  count: number
}

export default function UsersPage({ params }: { params: { locale: string } }) {
  const t = useTranslations('users')
  const [stats, setStats] = useState<AuditStats | null>(null)
  const [logs, setLogs] = useState<AuditLog[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    Promise.all([
      fetch(`${API_BASE}/api/v1/audit-logs/stats`).then(r => r.json()),
      fetch(`${API_BASE}/api/v1/audit-logs?page=1&page_size=20`).then(r => r.json()),
    ])
      .then(([statsData, logsData]: [AuditStats, AuditLogListResponse]) => {
        setStats(statsData)
        setLogs(logsData.logs ?? [])
        setLoading(false)
      })
      .catch(err => { setError(String(err)); setLoading(false) })
  }, [])

  const cardStyle = { background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 12, padding: '16px 18px' }

  return (
    <AppLayout locale={params.locale}>
      <div style={{ padding: '24px', background: '#f5f4ed', minHeight: '100%' }}>
        <div style={{ marginBottom: '20px' }}>
          <h1 style={{ fontSize: 18, fontWeight: 700, color: '#141413', margin: 0, fontFamily: 'var(--font-body), monospace' }}>{t('title')}</h1>
          <p style={{ fontSize: 12, color: '#87867f', margin: '4px 0 0', fontFamily: 'var(--font-body), monospace' }}>{t('subtitle')}</p>
        </div>

        {loading ? (
          <div style={{ padding: '32px', textAlign: 'center', color: '#87867f', fontFamily: 'var(--font-body), monospace', fontSize: 13 }}>{t('loading')}</div>
        ) : error ? (
          <div style={{ background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 12, padding: '32px', textAlign: 'center', color: '#cc2200', fontFamily: 'var(--font-body), monospace', fontSize: 13 }}>{t('error')}</div>
        ) : (
          <>
            {/* Stats Cards */}
            {stats && (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))', gap: 12, marginBottom: 16 }}>
                {[
                  { label: t('totalExecutions'), value: stats.total_executions },
                  { label: t('successCount'), value: stats.success_count },
                  { label: t('failureCount'), value: stats.failure_count },
                  { label: t('successRate'), value: `${(stats.success_rate * 100).toFixed(1)}%` },
                  { label: t('last24h'), value: stats.last_24h_count },
                  { label: t('avgDuration'), value: stats.avg_duration_ms ? `${stats.avg_duration_ms.toFixed(0)}ms` : '—' },
                ].map((card) => (
                  <div key={card.label} style={cardStyle}>
                    <div style={{ fontSize: 11, color: '#87867f', fontFamily: 'var(--font-body), monospace', marginBottom: 4, textTransform: 'uppercase', letterSpacing: '0.05em' }}>{card.label}</div>
                    <div style={{ fontSize: 22, fontWeight: 700, color: '#141413', fontFamily: 'var(--font-body), monospace' }}>{card.value}</div>
                  </div>
                ))}
              </div>
            )}

            {/* Recent Ops Table */}
            <div style={{ background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 12, overflow: 'hidden' }}>
              <div style={{ fontSize: 13, fontWeight: 700, padding: '10px 14px', borderBottom: '0.5px solid #e0ddd4', background: '#faf9f3', fontFamily: 'var(--font-body), monospace', color: '#141413' }}>
                {t('recentOps')} ({logs.length})
              </div>
              {logs.length === 0 ? (
                <div style={{ padding: '32px', textAlign: 'center', color: '#87867f', fontFamily: 'var(--font-body), monospace', fontSize: 13 }}>{t('noUsers')}</div>
              ) : (
                <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: 'var(--font-body), monospace', fontSize: 13 }}>
                  <thead>
                    <tr style={{ background: '#faf9f3' }}>
                      {[t('operation'), t('namespace'), t('result'), t('time')].map(col => (
                        <th key={col} style={{ padding: '8px 14px', textAlign: 'left', fontWeight: 600, color: '#87867f', borderBottom: '0.5px solid #e0ddd4', fontSize: 11 }}>{col}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {logs.map((log) => (
                      <tr key={log.id} style={{ borderBottom: '0.5px solid #f0ede4' }}>
                        <td style={{ padding: '7px 14px', fontWeight: 500, color: '#141413' }}>{log.operation_type}</td>
                        <td style={{ padding: '7px 14px', color: '#87867f' }}>{log.namespace ?? '—'}</td>
                        <td style={{ padding: '7px 14px' }}>
                          <span style={{ fontSize: 11, fontWeight: 600, color: log.success ? '#22C55E' : '#cc2200' }}>
                            {log.success ? '✓ OK' : '✗ FAIL'}
                          </span>
                        </td>
                        <td style={{ padding: '7px 14px', color: '#87867f', fontSize: 11 }}>
                          {new Date(log.created_at).toLocaleString('zh-TW', { timeZone: 'Asia/Taipei', month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' })}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </div>
          </>
        )}
      </div>
    </AppLayout>
  )
}
