import { useEffect, useState } from 'react'
import { guardiaApi } from '../api/clients'

export default function BillingManage() {
  const [sub, setSub] = useState<any>(null)
  const [usage, setUsage] = useState<any>(null)
  const [invoices, setInvoices] = useState<any[]>([])
  const [plans, setPlans] = useState<any[]>([])

  useEffect(() => { load() }, [])

  async function load() {
    const [s, u, i, p] = await Promise.all([
      guardiaApi.get('/api/billing/subscription').then((r: any) => r.data).catch(() => null),
      guardiaApi.get('/api/billing/usage').then((r: any) => r.data).catch(() => null),
      guardiaApi.get('/api/billing/invoices').then((r: any) => r.data).catch(() => []),
      guardiaApi.get('/api/billing/plans').then((r: any) => r.data).catch(() => []),
    ])
    setSub(s); setUsage(u); setInvoices(i || []); setPlans(p || [])
  }

  async function generateInvoice() {
    await guardiaApi.post('/api/billing/invoices/generate')
    load()
  }

  const pctColor = (pct: number) => pct > 90 ? '#ef4444' : pct > 70 ? '#f59e0b' : '#003366'

  return (
    <div style={{ padding: '24px 28px' }}>
      <h2 style={{ margin: '0 0 20px', fontSize: 20, fontWeight: 700 }}>💰 구독 · 과금 관리</h2>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 20 }}>
        {/* 현재 구독 */}
        <div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10, padding: 20 }}>
          <h3 style={{ fontSize: 14, fontWeight: 600, margin: '0 0 12px' }}>📋 현재 구독</h3>
          <div style={{ fontSize: 28, fontWeight: 700, color: '#003366' }}>{sub?.plan || 'COMMUNITY'}</div>
          <div style={{ fontSize: 13, color: '#64748b', marginTop: 4 }}>
            {sub?.price ? `월 ${sub.price.toLocaleString()}원` : '무료'} · {sub?.billing_cycle || 'MONTHLY'}
          </div>
          <div style={{ marginTop: 16, display: 'flex', gap: 8 }}>
            {plans.slice(0, 3).map((p: any) => (
              <button key={p.code} style={{
                padding: '6px 12px', borderRadius: 6, fontSize: 12, cursor: 'pointer',
                background: sub?.plan === p.code ? '#003366' : '#f8fafc',
                color: sub?.plan === p.code ? '#fff' : '#1e293b',
                border: `1px solid ${sub?.plan === p.code ? '#003366' : '#e2e8f0'}`,
              }}>
                {p.name}
              </button>
            ))}
          </div>
        </div>

        {/* 사용량 */}
        <div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10, padding: 20 }}>
          <h3 style={{ fontSize: 14, fontWeight: 600, margin: '0 0 12px' }}>📊 이번 달 사용량</h3>
          {usage && [
            { label: '서버', used: usage.servers?.used || 0, limit: usage.servers?.limit || 20 },
            { label: '사용자', used: usage.users?.used || 0, limit: usage.users?.limit || 10 },
          ].map(item => {
            const pct = item.limit > 0 ? Math.min(100, Math.round(item.used / item.limit * 100)) : 0
            return (
              <div key={item.label} style={{ marginBottom: 14 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 4 }}>
                  <span style={{ fontWeight: 600 }}>{item.label}</span>
                  <span style={{ color: pctColor(pct) }}>{item.used} / {item.limit < 0 ? '∞' : item.limit}</span>
                </div>
                <div style={{ background: '#f1f5f9', borderRadius: 4, height: 8 }}>
                  <div style={{ width: `${pct}%`, height: 8, background: pctColor(pct), borderRadius: 4, transition: 'width .4s' }} />
                </div>
              </div>
            )
          })}
          <div style={{ fontSize: 13, color: '#64748b' }}>SR (이번 달): {usage?.sr_this_month || 0}건</div>
        </div>
      </div>

      {/* 청구서 */}
      <div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10, padding: 20 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
          <h3 style={{ fontSize: 14, fontWeight: 600, margin: 0 }}>🧾 청구서 이력 ({invoices.length}건)</h3>
          <button onClick={generateInvoice} style={{ padding: '6px 14px', background: '#003366', color: '#fff', border: 'none', borderRadius: 6, cursor: 'pointer', fontSize: 12 }}>
            + 청구서 생성
          </button>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr style={{ borderBottom: '1px solid #e2e8f0' }}>
              {['기간', '플랜', '금액', '상태', '생성일'].map(h => (
                <th key={h} style={{ textAlign: 'left', padding: '8px 12px', fontSize: 11, fontWeight: 600, color: '#64748b' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {invoices.length === 0 ? (
              <tr><td colSpan={5} style={{ textAlign: 'center', padding: 24, color: '#94a3b8' }}>청구서 없음</td></tr>
            ) : invoices.slice(0, 12).map((inv: any) => (
              <tr key={inv.id} style={{ borderBottom: '1px solid #f1f5f9' }}>
                <td style={{ padding: '10px 12px' }}>{inv.period}</td>
                <td style={{ padding: '10px 12px' }}>{inv.plan || '-'}</td>
                <td style={{ padding: '10px 12px' }}>{inv.amount ? `${inv.amount.toLocaleString()}원` : '무료'}</td>
                <td style={{ padding: '10px 12px' }}>
                  <span style={{ background: inv.status === 'PAID' ? '#dcfce7' : '#fef3c7', color: inv.status === 'PAID' ? '#166534' : '#92400e', padding: '2px 8px', borderRadius: 10, fontSize: 11 }}>
                    {inv.status}
                  </span>
                </td>
                <td style={{ padding: '10px 12px', color: '#64748b', fontSize: 11 }}>
                  {inv.created_at ? new Date(inv.created_at).toLocaleDateString('ko-KR') : '-'}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}
