'use client'

/**
 * CostPanel — AI 執行效能統計面板 (不含 AppLayout)
 * ==================================================
 * Sprint 5: 從 /cost/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 AIPerformance {
  total_proposals: number
  executed_count: number
  execution_rate: number
  success_count: number
  success_rate: number
  avg_effectiveness: number | null
  effectiveness_distribution: Record<string, number>
}

export function CostPanel() {
  const t = useTranslations('cost')
  const [data, setData] = useState<AIPerformance | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    fetch(`${API_BASE}/api/v1/stats/ai-performance?days=30`)
      .then(r => r.json())
      .then((d: AIPerformance) => { setData(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>
      ) : data ? (
        <>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(160px, 1fr))', gap: 12, marginBottom: 16 }}>
            {[
              { label: t('totalProposals'), value: data.total_proposals },
              { label: t('executionRate'), value: `${(data.execution_rate).toFixed(1)}%` },
              { label: t('successRate'), value: `${(data.success_rate).toFixed(1)}%` },
              { label: t('avgEffectiveness'), value: data.avg_effectiveness ? data.avg_effectiveness.toFixed(2) : '—' },
            ].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>

          {data.effectiveness_distribution && Object.keys(data.effectiveness_distribution).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' }}>
                Effectiveness Distribution (1–5)
              </div>
              <div style={{ display: 'flex', gap: 0 }}>
                {[1, 2, 3, 4, 5].map(score => {
                  const count = data.effectiveness_distribution[String(score)] ?? 0
                  const barColors = ['#cc2200', '#F59E0B', '#87867f', '#4A90D9', '#22C55E']
                  return (
                    <div key={score} style={{ flex: 1, padding: '12px 14px', borderRight: '0.5px solid #f0ede4', textAlign: 'center' }}>
                      <div style={{ fontSize: 11, fontWeight: 700, color: barColors[score - 1], fontFamily: 'var(--font-body), monospace', marginBottom: 4 }}>★{score}</div>
                      <div style={{ fontSize: 20, fontWeight: 700, color: '#141413', fontFamily: 'var(--font-body), monospace' }}>{count}</div>
                    </div>
                  )
                })}
              </div>
            </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>
  )
}
