'use client'

/**
 * Action Log Page - K8s 操作稽核日誌
 * ==================================
 * Phase 4: 行動日誌介面
 *
 * Features:
 * - 真實 API 數據 (GET /api/v1/audit-logs)
 * - 分頁顯示
 * - 統計概覽
 * - 操作類型、狀態篩選
 * - 執行時間、耗時、簽核者資訊
 *
 * i18n: 100% next-intl，零硬編碼
 *
 * 版本: v1.1
 * 變更: 2026-03-31 (台北時區) - Claude Code
 *   - #19 P2: 新增 AbortController 防止 unmount 時記憶體洩漏
 */

import { useState, useEffect, useCallback, useRef } from 'react'
import { useTranslations } from 'next-intl'
import { AppLayout } from '@/components/layout'
import { DataPincerPanel } from '@/components/cyber'
import { cn } from '@/lib/utils'
import {
  FileText,
  CheckCircle2,
  XCircle,
  Clock,
  Activity,
  ChevronLeft,
  ChevronRight,
  RefreshCw,
  AlertCircle,
  Zap,
  TrendingUp,
} from 'lucide-react'

// =============================================================================
// Types
// =============================================================================

interface AuditLog {
  id: string
  approval_id: string
  operation_type: string
  target_resource: string
  namespace: string
  success: boolean
  error_message: string | null
  k8s_response: Record<string, unknown> | null
  executed_by: string
  execution_duration_ms: number | null
  dry_run_passed: boolean
  dry_run_message: string | null
  created_at: string
}

interface AuditLogListResponse {
  count: number
  logs: AuditLog[]
  page: number
  page_size: number
  total_pages: number
}

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

// =============================================================================
// API Helper
// =============================================================================

const getApiBaseUrl = (): string => {
  if (typeof window === 'undefined') return ''
  // 統帥鐵律: 禁止任何 Fallback IP
  const url = process.env.NEXT_PUBLIC_API_URL
  if (!url) {
    // eslint-disable-next-line no-console
    console.error('[AWOOOI ERROR] Missing NEXT_PUBLIC_API_URL')
    return ''
  }
  return url
}

// =============================================================================
// Stat Card Component
// =============================================================================

function StatCard({
  icon: Icon,
  label,
  value,
  subValue,
  variant = 'default',
}: {
  icon: typeof Activity
  label: string
  value: string | number
  subValue?: string
  variant?: 'default' | 'success' | 'warning'
}) {
  return (
    <div
      className={cn(
        'rounded-lg border p-4',
        'bg-white/50 backdrop-blur-sm',
        variant === 'success' && 'border-status-healthy/30',
        variant === 'warning' && 'border-status-warning/30',
        variant === 'default' && 'border-nothing-gray-200'
      )}
    >
      <div className="flex items-center gap-3">
        <div
          className={cn(
            'w-10 h-10 rounded-lg flex items-center justify-center',
            variant === 'success' && 'bg-status-healthy/10',
            variant === 'warning' && 'bg-status-warning/10',
            variant === 'default' && 'bg-nothing-gray-100'
          )}
        >
          <Icon
            className={cn(
              'w-5 h-5',
              variant === 'success' && 'text-status-healthy',
              variant === 'warning' && 'text-status-warning',
              variant === 'default' && 'text-nothing-gray-600'
            )}
          />
        </div>
        <div>
          <p className="text-xs text-nothing-gray-500 font-mono uppercase">
            {label}
          </p>
          <p className="text-xl font-bold text-nothing-black">{value}</p>
          {subValue && (
            <p className="text-[10px] text-nothing-gray-400 font-mono">
              {subValue}
            </p>
          )}
        </div>
      </div>
    </div>
  )
}

// =============================================================================
// Main Component
// =============================================================================

export default function ActionLogPage({
  params,
}: {
  params: { locale: string }
}) {
  const t = useTranslations()
  const locale = params.locale

  // State
  const [logs, setLogs] = useState<AuditLog[]>([])
  const [stats, setStats] = useState<AuditStats | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [totalCount, setTotalCount] = useState(0)

  // #19 P2: AbortController 防止 unmount 時記憶體洩漏
  const abortControllerRef = useRef<AbortController | null>(null)

  // ==========================================================================
  // Fetch Audit Logs
  // ==========================================================================
  const fetchLogs = useCallback(async (pageNum: number) => {
    const apiBaseUrl = getApiBaseUrl()
    if (!apiBaseUrl) return

    // 取消前一次未完成的請求
    abortControllerRef.current?.abort()
    const controller = new AbortController()
    abortControllerRef.current = controller

    setIsLoading(true)
    setError(null)

    try {
      const response = await fetch(
        `${apiBaseUrl}/api/v1/audit-logs?page=${pageNum}&page_size=10`,
        {
          headers: { 'Content-Type': 'application/json' },
          signal: controller.signal,
        }
      )

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

      const data: AuditLogListResponse = await response.json()
      setLogs(data.logs)
      setPage(data.page)
      setTotalPages(data.total_pages)
      setTotalCount(data.count)
    } catch (err) {
      // 忽略 AbortError (正常行為)
      if (err instanceof Error && err.name === 'AbortError') {
        return
      }
      const message = err instanceof Error ? err.message : 'Unknown error'
      setError(message)
      console.error('[ActionLog] Fetch error:', message) // eslint-disable-line no-console
    } finally {
      setIsLoading(false)
    }
  }, [])

  // ==========================================================================
  // Fetch Stats
  // ==========================================================================
  const fetchStats = useCallback(async () => {
    const apiBaseUrl = getApiBaseUrl()
    if (!apiBaseUrl) return

    try {
      const response = await fetch(`${apiBaseUrl}/api/v1/audit-logs/stats`, {
        headers: { 'Content-Type': 'application/json' },
        signal: abortControllerRef.current?.signal,
      })

      if (response.ok) {
        const data: AuditStats = await response.json()
        setStats(data)
      }
    } catch (err) {
      // 忽略 AbortError
      if (err instanceof Error && err.name === 'AbortError') {
        return
      }
      console.error('[ActionLog] Stats fetch error:', err) // eslint-disable-line no-console
    }
  }, [])

  // ==========================================================================
  // Initial Fetch + Cleanup
  // ==========================================================================
  useEffect(() => {
    fetchLogs(1)
    fetchStats()

    // #19 P2: Cleanup - 組件 unmount 時取消所有請求
    return () => {
      abortControllerRef.current?.abort()
    }
  }, [fetchLogs, fetchStats])

  // ==========================================================================
  // Pagination Handlers
  // ==========================================================================
  const handlePrevPage = () => {
    if (page > 1) {
      fetchLogs(page - 1)
    }
  }

  const handleNextPage = () => {
    if (page < totalPages) {
      fetchLogs(page + 1)
    }
  }

  // ==========================================================================
  // Format Helpers
  // ==========================================================================
  const formatDate = (isoString: string) => {
    try {
      const date = new Date(isoString)
      return date.toLocaleString(locale === 'zh-TW' ? 'zh-TW' : 'en-US', {
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
      })
    } catch {
      return isoString
    }
  }

  const formatDuration = (ms: number | null) => {
    if (ms === null) return '-'
    if (ms < 1000) return `${ms}ms`
    return `${(ms / 1000).toFixed(2)}s`
  }

  // ==========================================================================
  // Render
  // ==========================================================================
  return (
    <AppLayout locale={locale}>
      {/* Page Title */}
      <div className="mb-6">
        <h2 className="font-heading text-2xl font-bold text-nothing-black">
          {t('actionLog.title')}
        </h2>
        <p className="mt-1 text-sm text-nothing-gray-500">
          {t('actionLog.subtitle')}
        </p>
      </div>

      {/* Stats Overview */}
      {stats && (
        <div className="mb-6 grid grid-cols-2 md:grid-cols-4 gap-4">
          <StatCard
            icon={Activity}
            label={t('actionLog.stats.total')}
            value={stats.total_executions}
          />
          <StatCard
            icon={TrendingUp}
            label={t('actionLog.stats.successRate')}
            value={`${stats.success_rate}%`}
            variant="success"
          />
          <StatCard
            icon={Clock}
            label={t('actionLog.stats.avgDuration')}
            value={stats.avg_duration_ms ? `${Math.round(stats.avg_duration_ms)}ms` : '-'}
          />
          <StatCard
            icon={Zap}
            label={t('actionLog.stats.last24h')}
            value={stats.last_24h_count}
            variant="warning"
          />
        </div>
      )}

      {/* Main Content */}
      <DataPincerPanel title={t('actionLog.title')} status="healthy">
        {/* Toolbar */}
        <div className="flex items-center justify-between mb-4 px-1">
          <div className="text-sm text-nothing-gray-500 font-mono">
            {totalCount > 0
              ? `${totalCount} ${t('actionLog.columns.operation').toLowerCase()}s`
              : ''}
          </div>
          <button
            onClick={() => {
              fetchLogs(page)
              fetchStats()
            }}
            disabled={isLoading}
            className={cn(
              'flex items-center gap-1 px-3 py-1.5 rounded-lg text-xs font-mono',
              'bg-nothing-gray-100 text-nothing-gray-600',
              'hover:bg-nothing-gray-200 transition-colors',
              'disabled:opacity-50 disabled:cursor-not-allowed'
            )}
          >
            <RefreshCw
              className={cn('w-3 h-3', isLoading && 'animate-spin')}
            />
            {t('common.refresh')}
          </button>
        </div>

        {/* Error State */}
        {error && (
          <div className="flex items-center gap-2 p-4 mb-4 rounded-lg bg-status-critical/10 border border-status-critical/20">
            <AlertCircle className="w-4 h-4 text-status-critical" />
            <span className="text-sm text-status-critical font-mono">
              {t('actionLog.fetchError')}: {error}
            </span>
          </div>
        )}

        {/* Loading State */}
        {isLoading && logs.length === 0 && (
          <div className="flex items-center justify-center py-12">
            <RefreshCw className="w-6 h-6 text-nothing-gray-400 animate-spin" />
            <span className="ml-2 text-nothing-gray-400 font-mono">
              {t('actionLog.loading')}
            </span>
          </div>
        )}

        {/* Empty State */}
        {!isLoading && logs.length === 0 && !error && (
          <div className="text-center py-12">
            <FileText className="w-12 h-12 mx-auto mb-3 text-nothing-gray-300" />
            <p className="text-nothing-gray-400 font-mono">
              {t('actionLog.noLogs')}
            </p>
          </div>
        )}

        {/* Logs Table */}
        {logs.length > 0 && (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-nothing-gray-200">
                  <th className="px-3 py-2 text-left font-mono text-[10px] uppercase text-nothing-gray-500">
                    {t('actionLog.columns.time')}
                  </th>
                  <th className="px-3 py-2 text-left font-mono text-[10px] uppercase text-nothing-gray-500">
                    {t('actionLog.columns.operation')}
                  </th>
                  <th className="px-3 py-2 text-left font-mono text-[10px] uppercase text-nothing-gray-500">
                    {t('actionLog.columns.target')}
                  </th>
                  <th className="px-3 py-2 text-left font-mono text-[10px] uppercase text-nothing-gray-500">
                    {t('actionLog.columns.namespace')}
                  </th>
                  <th className="px-3 py-2 text-center font-mono text-[10px] uppercase text-nothing-gray-500">
                    {t('actionLog.columns.status')}
                  </th>
                  <th className="px-3 py-2 text-right font-mono text-[10px] uppercase text-nothing-gray-500">
                    {t('actionLog.columns.duration')}
                  </th>
                  <th className="px-3 py-2 text-left font-mono text-[10px] uppercase text-nothing-gray-500">
                    {t('actionLog.columns.executor')}
                  </th>
                </tr>
              </thead>
              <tbody>
                {logs.map((log) => (
                  <tr
                    key={log.id}
                    className="border-b border-nothing-gray-100 hover:bg-nothing-gray-50/50 transition-colors"
                  >
                    <td className="px-3 py-3 font-mono text-xs text-nothing-gray-600">
                      {formatDate(log.created_at)}
                    </td>
                    <td className="px-3 py-3">
                      <span
                        className={cn(
                          'inline-flex items-center px-2 py-0.5 rounded text-[10px] font-mono font-bold uppercase',
                          log.operation_type === 'DELETE_POD' &&
                            'bg-status-critical/10 text-status-critical',
                          log.operation_type === 'RESTART_DEPLOYMENT' &&
                            'bg-status-warning/10 text-status-warning',
                          log.operation_type === 'SCALE_DEPLOYMENT' &&
                            'bg-claw-blue/10 text-claw-blue'
                        )}
                      >
                        {t(`actionLog.operations.${log.operation_type}` as never) ||
                          log.operation_type}
                      </span>
                    </td>
                    <td className="px-3 py-3 font-mono text-xs text-nothing-black max-w-[200px] truncate">
                      {log.target_resource}
                    </td>
                    <td className="px-3 py-3 font-mono text-xs text-nothing-gray-600">
                      {log.namespace}
                    </td>
                    <td className="px-3 py-3 text-center">
                      {log.success ? (
                        <span className="inline-flex items-center gap-1 text-status-healthy">
                          <CheckCircle2 className="w-4 h-4" />
                          <span className="text-[10px] font-mono uppercase">
                            {t('actionLog.status.success')}
                          </span>
                        </span>
                      ) : (
                        <span className="inline-flex items-center gap-1 text-status-critical">
                          <XCircle className="w-4 h-4" />
                          <span className="text-[10px] font-mono uppercase">
                            {t('actionLog.status.failure')}
                          </span>
                        </span>
                      )}
                    </td>
                    <td className="px-3 py-3 text-right font-mono text-xs text-nothing-gray-600">
                      {formatDuration(log.execution_duration_ms)}
                    </td>
                    <td className="px-3 py-3 font-mono text-xs text-nothing-gray-600">
                      {log.executed_by}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between mt-4 px-1">
            <span className="text-xs text-nothing-gray-500 font-mono">
              {t('actionLog.pagination.page', {
                current: page,
                total: totalPages,
              })}
            </span>
            <div className="flex items-center gap-2">
              <button
                onClick={handlePrevPage}
                disabled={page <= 1 || isLoading}
                className={cn(
                  'flex items-center gap-1 px-3 py-1.5 rounded-lg text-xs font-mono',
                  'border border-nothing-gray-200',
                  'hover:bg-nothing-gray-50 transition-colors',
                  'disabled:opacity-50 disabled:cursor-not-allowed'
                )}
              >
                <ChevronLeft className="w-3 h-3" />
                {t('actionLog.pagination.prev')}
              </button>
              <button
                onClick={handleNextPage}
                disabled={page >= totalPages || isLoading}
                className={cn(
                  'flex items-center gap-1 px-3 py-1.5 rounded-lg text-xs font-mono',
                  'border border-nothing-gray-200',
                  'hover:bg-nothing-gray-50 transition-colors',
                  'disabled:opacity-50 disabled:cursor-not-allowed'
                )}
              >
                {t('actionLog.pagination.next')}
                <ChevronRight className="w-3 h-3" />
              </button>
            </div>
          </div>
        )}
      </DataPincerPanel>

      {/* Footer */}
      <footer className="mt-12 pt-6 border-t border-nothing-gray-200">
        <div className="flex flex-col sm:flex-row items-center justify-between gap-4">
          <p className="text-sm text-nothing-gray-500">
            {t('footer.copyright')}
          </p>
          <p className="text-sm text-nothing-gray-400 font-mono">
            {t('footer.poweredBy')} v1.0.0
          </p>
        </div>
      </footer>
    </AppLayout>
  )
}
