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

interface Payout {
  id: number
  execution_id: number
  skill_id: string
  author_id: string | null
  role: 'chain' | 'dep'
  step_num: number | null
  weight: number
  gross_revenue_eur: number
  author_share_eur: number
  status: string
  created_at: string
}

export default function MarketplacePayouts() {
  const [payouts, setPayouts] = useState<Payout[]>([])
  const [loading, setLoading] = useState(true)
  const [marking, setMarking] = useState<number | null>(null)

  const load = () => {
    setLoading(true)
    fetch('/bibividi/api/marketplace/payouts')
      .then(r => r.json())
      .then(setPayouts)
      .catch(() => {})
      .finally(() => setLoading(false))
  }

  const markPaid = (id: number) => {
    setMarking(id)
    fetch(`/bibividi/api/marketplace/payouts/${id}/pay`, { method: 'POST' })
      .then(() => load())
      .catch(() => {})
      .finally(() => setMarking(null))
  }

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

  const totalPending = payouts.reduce((s, p) => s + p.author_share_eur, 0)

  return (
    <div>
      <div className="page-title">
        <Store size={20} color="var(--accent-light)" />
        Marketplace Payouts
        <button className="btn btn-ghost" style={{ marginLeft: 'auto', padding: '5px 10px' }} onClick={load}>
          <RefreshCw size={13} />
        </button>
      </div>

      {!loading && payouts.length > 0 && (
        <div className="kpi-card" style={{ maxWidth: 280, marginBottom: 16 }}>
          <div className="kpi-label" style={{ marginBottom: 4 }}>Total Pending Payouts</div>
          <div className="kpi-value yellow">€{totalPending.toFixed(4)}</div>
        </div>
      )}

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

      {!loading && payouts.length === 0 && (
        <div className="empty-state">
          <Store size={32} />
          <p>No pending payouts.</p>
          <p className="fine" style={{ marginTop: 4 }}>
            Payouts are created when paid chain skills execute.
          </p>
        </div>
      )}

      {!loading && payouts.length > 0 && (
        <div className="section">
          <div style={{ overflowX: 'auto' }}>
            <table className="data-table">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>Skill</th>
                  <th>Author</th>
                  <th>Role</th>
                  <th>Weight</th>
                  <th>Gross (€)</th>
                  <th>Share (€)</th>
                  <th>Created</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {payouts.map(p => (
                  <tr key={p.id}>
                    <td className="muted fine">{p.id}</td>
                    <td className="mono">{p.skill_id}</td>
                    <td className="mono fine">
                      {p.author_id
                        ? <span title={p.author_id}>{p.author_id.slice(0, 14)}…</span>
                        : <span className="muted">—</span>
                      }
                    </td>
                    <td>
                      <span className={`badge ${p.role === 'chain' ? 'badge-purple' : 'badge-gray'}`}>
                        {p.role}
                      </span>
                    </td>
                    <td>{(p.weight * 100).toFixed(1)}%</td>
                    <td>€{p.gross_revenue_eur.toFixed(4)}</td>
                    <td className="green">€{p.author_share_eur.toFixed(4)}</td>
                    <td className="muted fine nowrap">{p.created_at.slice(0, 10)}</td>
                    <td>
                      <button
                        className="btn btn-success"
                        style={{ padding: '3px 10px', fontSize: 12 }}
                        onClick={() => markPaid(p.id)}
                        disabled={marking === p.id}
                      >
                        <CheckCircle size={12} />
                        {marking === p.id ? '…' : 'Paid'}
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  )
}
