import { useEffect, useState } from 'react'
import { CreditCard, RefreshCw } from 'lucide-react'

interface BillingSummary {
  year: number
  month: number
  tier: string
  savings_eur: number
  bibividi_share_eur: number
  net_eur: number
  tokens_saved: number
  executions: number
  capped: boolean
}

const MONTHS = [
  'January','February','March','April','May','June',
  'July','August','September','October','November','December',
]

export default function Billing() {
  const now = new Date()
  const [year, setYear]   = useState(now.getFullYear())
  const [month, setMonth] = useState(now.getMonth() + 1)
  const [data, setData]   = useState<BillingSummary | null>(null)
  const [loading, setLoading] = useState(false)

  const load = () => {
    setLoading(true)
    fetch(`/bibividi/api/billing/summary?year=${year}&month=${month}`)
      .then(r => r.json())
      .then(setData)
      .catch(() => {})
      .finally(() => setLoading(false))
  }

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

  const years = Array.from({ length: 3 }, (_, i) => now.getFullYear() - i)

  return (
    <div>
      <div className="page-title">
        <CreditCard size={20} color="var(--accent-light)" />
        Billing
      </div>

      {/* Month picker */}
      <div className="month-picker">
        <select value={month} onChange={e => setMonth(+e.target.value)}>
          {MONTHS.map((m, i) => (
            <option key={i + 1} value={i + 1}>{m}</option>
          ))}
        </select>
        <select value={year} onChange={e => setYear(+e.target.value)}>
          {years.map(y => <option key={y} value={y}>{y}</option>)}
        </select>
        <button className="btn btn-ghost" style={{ padding: '5px 10px' }} onClick={load}>
          <RefreshCw size={13} />
        </button>
      </div>

      {loading && <p className="muted">Loading…</p>}

      {!loading && data && (
        <div style={{ maxWidth: 520 }}>
          {/* Header card */}
          <div className="kpi-card" style={{ marginBottom: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span className="muted fine">
                {MONTHS[data.month - 1]} {data.year}
              </span>
              <span className="badge badge-purple">{data.tier}</span>
            </div>
            <div className="kpi-value green" style={{ marginTop: 8 }}>
              €{data.net_eur.toFixed(2)}
            </div>
            <div className="kpi-label">Net savings after BIBIVIDI fee</div>
          </div>

          {/* Breakdown */}
          <div className="section">
            <div className="section-header"><CreditCard size={13} /> Breakdown</div>
            <div className="section-body">
              <div className="billing-row">
                <span className="label">Tokens saved</span>
                <span className="value">{data.tokens_saved.toLocaleString()}</span>
              </div>
              <div className="billing-row">
                <span className="label">Executions</span>
                <span className="value">{data.executions.toLocaleString()}</span>
              </div>
              <div className="billing-row">
                <span className="label">Gross savings</span>
                <span className="value green">€{data.savings_eur.toFixed(4)}</span>
              </div>
              <div className="billing-row">
                <span className="label">
                  BIBIVIDI fee{data.capped && <span className="badge badge-gray" style={{ marginLeft: 6 }}>capped</span>}
                </span>
                <span className="value">€{data.bibividi_share_eur.toFixed(4)}</span>
              </div>
              <div className="billing-row">
                <span className="label" style={{ fontWeight: 600 }}>Your net savings</span>
                <span className="value green" style={{ fontSize: 15 }}>€{data.net_eur.toFixed(4)}</span>
              </div>
            </div>
          </div>

          <p className="muted fine" style={{ marginTop: 8 }}>
            Savings-share pricing · Tier rates: free 0% · pro 20% · growth 15% · enterprise 10%
          </p>
        </div>
      )}
    </div>
  )
}
