'use client';

import React from 'react';
import { t } from '@/i18n/locales';
import { useApi } from '@/lib/use-api';

/**
 * D3. 财务管理 - 平台级财务总览
 *
 * 平台收入（手续费）、发行方结算、消费者退款、资金池监控
 */

interface FinanceSummary {
  platformFee: number;
  pendingSettlement: number;
  consumerRefund: number;
  poolBalance: number;
}

interface Settlement {
  issuer: string;
  amount: number;
  status: string;
  time: string;
}

const loadingBox: React.CSSProperties = {
  display: 'flex', alignItems: 'center', justifyContent: 'center',
  padding: 40, color: 'var(--color-text-tertiary)', font: 'var(--text-body)',
};

export const FinanceManagementPage: React.FC = () => {
  const { data: summaryData, isLoading: summaryLoading, error: summaryError } = useApi<FinanceSummary>('/api/v1/admin/finance/summary');
  const { data: settlementsData, isLoading: settlementsLoading } = useApi<Settlement[]>('/api/v1/admin/finance/settlements');

  const formatCurrency = (n: number) => `$${n?.toLocaleString() ?? '0'}`;

  const financeStats = summaryData ? [
    { label: t('finance_platform_fee'), value: formatCurrency(summaryData.platformFee), period: t('finance_period_month'), color: 'var(--color-success)' },
    { label: t('finance_pending_settlement'), value: formatCurrency(summaryData.pendingSettlement), period: t('finance_period_cumulative'), color: 'var(--color-warning)' },
    { label: t('finance_consumer_refund'), value: formatCurrency(summaryData.consumerRefund), period: t('finance_period_month'), color: 'var(--color-error)' },
    { label: t('finance_pool_balance'), value: formatCurrency(summaryData.poolBalance), period: t('finance_period_realtime'), color: 'var(--color-primary)' },
  ] : [];

  if (summaryError) {
    return <div style={loadingBox}>Error: {summaryError.message}</div>;
  }

  return (
    <div>
      <h1 style={{ font: 'var(--text-h1)', color: 'var(--color-text-primary)', marginBottom: 24 }}>{t('finance_title')}</h1>

      {/* Stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }}>
        {summaryLoading ? (
          <div style={{ ...loadingBox, gridColumn: '1 / -1' }}>Loading...</div>
        ) : financeStats.map(s => (
          <div key={s.label} style={{
            background: 'var(--color-surface)', borderRadius: 'var(--radius-md)',
            border: '1px solid var(--color-border-light)', padding: 20,
          }}>
            <div style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)', marginBottom: 8 }}>{s.label}</div>
            <div style={{ font: 'var(--text-h1)', color: s.color }}>{s.value}</div>
            <div style={{ font: 'var(--text-caption)', color: 'var(--color-text-tertiary)', marginTop: 4 }}>{s.period}</div>
          </div>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
        {/* Settlement Queue */}
        <div style={{
          background: 'var(--color-surface)', borderRadius: 'var(--radius-md)',
          border: '1px solid var(--color-border-light)', padding: 20,
        }}>
          <h2 style={{ font: 'var(--text-h2)', marginBottom: 16 }}>{t('finance_settlement_queue')}</h2>
          {settlementsLoading ? (
            <div style={loadingBox}>Loading...</div>
          ) : (
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr>{[t('finance_th_issuer'), t('finance_th_amount'), t('finance_th_status'), t('finance_th_time')].map(h => (
                  <th key={h} style={{ padding: '8px 0', textAlign: 'left', font: 'var(--text-label-sm)', color: 'var(--color-text-tertiary)', borderBottom: '1px solid var(--color-border-light)' }}>{h}</th>
                ))}</tr>
              </thead>
              <tbody>
                {(settlementsData ?? []).map((s, i) => (
                  <tr key={i} style={{ borderBottom: '1px solid var(--color-border-light)' }}>
                    <td style={{ padding: '10px 0', font: 'var(--text-body)' }}>{s.issuer}</td>
                    <td style={{ padding: '10px 0', font: 'var(--text-label)', color: 'var(--color-primary)' }}>${s.amount?.toLocaleString()}</td>
                    <td style={{ padding: '10px 0' }}>
                      <span style={{
                        padding: '2px 8px', borderRadius: 'var(--radius-full)', font: 'var(--text-caption)', fontWeight: 600,
                        background: s.status === 'settled' ? 'var(--color-success-light)' : s.status === 'processing' ? 'var(--color-info-light)' : 'var(--color-warning-light)',
                        color: s.status === 'settled' ? 'var(--color-success)' : s.status === 'processing' ? 'var(--color-info)' : 'var(--color-warning)',
                      }}>
                        {s.status === 'settled' ? t('finance_status_settled') : s.status === 'processing' ? t('finance_status_processing') : t('finance_status_pending')}
                      </span>
                    </td>
                    <td style={{ padding: '10px 0', font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)' }}>{s.time}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>

        {/* Revenue Chart Placeholder */}
        <div style={{
          background: 'var(--color-surface)', borderRadius: 'var(--radius-md)',
          border: '1px solid var(--color-border-light)', padding: 20,
        }}>
          <h2 style={{ font: 'var(--text-h2)', marginBottom: 16 }}>{t('finance_revenue_trend')}</h2>
          <div style={{
            height: 240, background: 'var(--color-gray-50)', borderRadius: 'var(--radius-sm)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: 'var(--color-text-tertiary)', font: 'var(--text-body)',
          }}>
            月度手续费收入趋势图
          </div>
        </div>
      </div>
    </div>
  );
};
