'use client'

/**
 * BillingPanel — 系統操作使用量面板 (不含 AppLayout)
 * ====================================================
 * Sprint 5: 從 /billing/page.tsx 抽取
 * 供原始頁面和整合頁面 (/operations) 共用
 *
 * 建立時間: 2026-04-09 (台北時區)
 */

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

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

export function BillingPanel() {
  const t = useTranslations('billing')
  const [stats, setStats] = useState<AuditStats | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    fetch(`${API_BASE}/api/v1/audit-logs/stats`)
      .then(r => r.json())
      .then((d: AuditStats) => { setStats(d); setLoading(false) })
      .catch(err => { setError(String(err)); setLoading(false) })
  }, [])

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

  return (
    <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 ? (
        <>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))', gap: 12, marginBottom: 16 }}>
            {[
              { label: t('totalUsage'), value: stats.total_executions },
              { label: t('last24h'), value: stats.last_24h_count },
              { label: t('successRate'), value: `${(stats.success_rate * 100).toFixed(1)}%` },
              { 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: 24, fontWeight: 700, color: '#141413', fontFamily: 'var(--font-body), monospace' }}>{card.value}</div>
              </div>
            ))}
          </div>

          {Object.keys(stats.by_operation_type).length > 0 && (
            <div style={{ background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 12, overflow: 'hidden', marginBottom: 12 }}>
              <div style={{ fontSize: 13, fontWeight: 700, padding: '10px 14px', borderBottom: '0.5px solid #e0ddd4', background: '#faf9f3', fontFamily: 'var(--font-body), monospace', color: '#141413' }}>
                By Operation Type
              </div>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: 'var(--font-body), monospace', fontSize: 13 }}>
                <tbody>
                  {Object.entries(stats.by_operation_type).sort(([, a], [, b]) => b - a).map(([op, count]) => (
                    <tr key={op} style={{ borderBottom: '0.5px solid #f0ede4' }}>
                      <td style={{ padding: '7px 14px', fontWeight: 500, color: '#141413' }}>{op}</td>
                      <td style={{ padding: '7px 14px', color: '#87867f', textAlign: 'right' }}>{count}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          {Object.keys(stats.by_namespace).length > 0 && (
            <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' }}>
                By Namespace
              </div>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: 'var(--font-body), monospace', fontSize: 13 }}>
                <tbody>
                  {Object.entries(stats.by_namespace).sort(([, a], [, b]) => b - a).map(([ns, count]) => (
                    <tr key={ns} style={{ borderBottom: '0.5px solid #f0ede4' }}>
                      <td style={{ padding: '7px 14px', fontWeight: 500, color: '#141413' }}>{ns}</td>
                      <td style={{ padding: '7px 14px', color: '#87867f', textAlign: 'right' }}>{count}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </>
      ) : (
        <div style={{ background: '#fff', border: '0.5px solid #e0ddd4', borderRadius: 12, padding: '32px', textAlign: 'center', color: '#87867f', fontFamily: 'var(--font-body), monospace', fontSize: 13 }}>{t('noData')}</div>
      )}
    </div>
  )
}
