'use client';

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

/**
 * D1. 平台运营仪表盘
 *
 * 平台总交易量/金额、活跃用户数、发行方数量、券流通总量、
 * 实时交易流、系统健康状态
 */

interface DashboardStats {
  totalVolume: number;
  totalAmount: number;
  activeUsers: number;
  issuerCount: number;
  couponCirculation: number;
  systemHealthPercent: number;
  totalVolumeChange: string;
  totalAmountChange: string;
  activeUsersChange: string;
  issuerCountChange: string;
  couponCirculationChange: string;
}

interface RealtimeTrade {
  time: string;
  type: string;
  orderId: string;
  amount: number;
  status: string;
}

interface ServiceHealth {
  name: string;
  status: 'healthy' | 'warning' | 'error';
  latency: string;
}

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

export const DashboardPage: React.FC = () => {
  const { data: statsData, isLoading: statsLoading, error: statsError } = useApi<DashboardStats>('/api/v1/admin/dashboard/stats');
  const { data: tradesData, isLoading: tradesLoading } = useApi<RealtimeTrade[]>('/api/v1/admin/dashboard/realtime-trades');
  const { data: healthData, isLoading: healthLoading } = useApi<ServiceHealth[]>('/api/v1/admin/dashboard/system-health');

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

  const stats = statsData ? [
    { label: t('dashboard_total_volume'), value: formatNumber(statsData.totalVolume), change: statsData.totalVolumeChange, trend: statsData.totalVolumeChange?.startsWith('-') ? 'down' as const : 'up' as const, color: 'var(--color-primary)' },
    { label: t('dashboard_total_amount'), value: formatCurrency(statsData.totalAmount), change: statsData.totalAmountChange, trend: statsData.totalAmountChange?.startsWith('-') ? 'down' as const : 'up' as const, color: 'var(--color-success)' },
    { label: t('dashboard_active_users'), value: formatNumber(statsData.activeUsers), change: statsData.activeUsersChange, trend: statsData.activeUsersChange?.startsWith('-') ? 'down' as const : 'up' as const, color: 'var(--color-info)' },
    { label: t('dashboard_issuer_count'), value: formatNumber(statsData.issuerCount), change: statsData.issuerCountChange, trend: statsData.issuerCountChange?.startsWith('-') ? 'down' as const : 'up' as const, color: 'var(--color-warning)' },
    { label: t('dashboard_coupon_circulation'), value: formatNumber(statsData.couponCirculation), change: statsData.couponCirculationChange, trend: statsData.couponCirculationChange?.startsWith('-') ? 'down' as const : 'up' as const, color: 'var(--color-primary-dark)' },
    { label: t('dashboard_system_health'), value: `${statsData.systemHealthPercent}%`, change: 'Normal', trend: 'up' as const, color: 'var(--color-success)' },
  ] : [];

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

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

      {/* Stats Grid */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(3, 1fr)',
        gap: 16,
        marginBottom: 24,
      }}>
        {statsLoading ? (
          <div style={{ ...loadingBox, gridColumn: '1 / -1' }}>Loading...</div>
        ) : stats.map(stat => (
          <div key={stat.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 }}>
              {stat.label}
            </div>
            <div style={{ font: 'var(--text-h1)', color: stat.color }}>
              {stat.value}
            </div>
            <div style={{
              font: 'var(--text-label-sm)',
              color: stat.trend === 'up' ? 'var(--color-success)' : 'var(--color-error)',
              marginTop: 4,
            }}>
              {stat.change}
            </div>
          </div>
        ))}
      </div>

      {/* Charts Row */}
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 16, marginBottom: 24 }}>
        {/* Transaction Volume Chart */}
        <div style={{
          background: 'var(--color-surface)',
          borderRadius: 'var(--radius-md)',
          border: '1px solid var(--color-border-light)',
          padding: 20,
        }}>
          <div style={{ font: 'var(--text-h3)', marginBottom: 16 }}>{t('dashboard_volume_trend')}</div>
          <div style={{
            height: 240,
            background: 'var(--color-gray-50)',
            borderRadius: 'var(--radius-sm)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: 'var(--color-text-tertiary)',
          }}>
            Recharts / ECharts 折线图
          </div>
        </div>

        {/* Transaction Type Pie */}
        <div style={{
          background: 'var(--color-surface)',
          borderRadius: 'var(--radius-md)',
          border: '1px solid var(--color-border-light)',
          padding: 20,
        }}>
          <div style={{ font: 'var(--text-h3)', marginBottom: 16 }}>{t('dashboard_type_distribution')}</div>
          <div style={{
            height: 240,
            background: 'var(--color-gray-50)',
            borderRadius: 'var(--radius-sm)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: 'var(--color-text-tertiary)',
          }}>
            饼图 (一级/二级/核销/转赠)
          </div>
        </div>
      </div>

      {/* Real-time Transaction Feed + System Health */}
      <div style={{ display: 'grid', gridTemplateColumns: '3fr 1fr', gap: 16 }}>
        {/* Real-time Feed */}
        <div style={{
          background: 'var(--color-surface)',
          borderRadius: 'var(--radius-md)',
          border: '1px solid var(--color-border-light)',
          padding: 20,
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
            <div style={{ font: 'var(--text-h3)' }}>{t('dashboard_realtime_feed')}</div>
            <span style={{
              width: 8, height: 8,
              borderRadius: '50%',
              background: 'var(--color-success)',
              display: 'inline-block',
              animation: 'pulse 2s infinite',
            }} />
          </div>
          {tradesLoading ? (
            <div style={loadingBox}>Loading...</div>
          ) : (
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr style={{ borderBottom: '1px solid var(--color-border-light)' }}>
                  {[t('dashboard_th_time'), t('dashboard_th_type'), t('dashboard_th_order'), t('dashboard_th_amount'), t('dashboard_th_status')].map(h => (
                    <th key={h} style={{
                      font: 'var(--text-label-sm)',
                      color: 'var(--color-text-tertiary)',
                      padding: '8px 12px',
                      textAlign: 'left',
                    }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {(tradesData ?? []).map((row, i) => (
                  <tr key={i} style={{ borderBottom: '1px solid var(--color-border-light)' }}>
                    <td style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)', padding: '10px 12px' }}>{row.time}</td>
                    <td style={{ font: 'var(--text-label-sm)', padding: '10px 12px' }}>{row.type}</td>
                    <td style={{ font: 'var(--text-body-sm)', fontFamily: 'var(--font-family-mono)', padding: '10px 12px' }}>{row.orderId}</td>
                    <td style={{ font: 'var(--text-label-sm)', color: 'var(--color-primary)', padding: '10px 12px' }}>${row.amount?.toFixed(2)}</td>
                    <td style={{ padding: '10px 12px' }}>
                      <span style={{
                        padding: '2px 8px',
                        borderRadius: 'var(--radius-full)',
                        font: 'var(--text-caption)',
                        background: row.status === 'completed' ? 'var(--color-success-light)' : 'var(--color-warning-light)',
                        color: row.status === 'completed' ? 'var(--color-success)' : 'var(--color-warning)',
                      }}>
                        {row.status === 'completed' ? t('dashboard_status_completed') : t('dashboard_status_processing')}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>

        {/* System Health */}
        <div style={{
          background: 'var(--color-surface)',
          borderRadius: 'var(--radius-md)',
          border: '1px solid var(--color-border-light)',
          padding: 20,
        }}>
          <div style={{ font: 'var(--text-h3)', marginBottom: 16 }}>{t('dashboard_system_health')}</div>
          {healthLoading ? (
            <div style={loadingBox}>Loading...</div>
          ) : (healthData ?? []).map(service => (
            <div key={service.name} style={{
              display: 'flex',
              alignItems: 'center',
              padding: '10px 0',
              borderBottom: '1px solid var(--color-border-light)',
            }}>
              <span style={{
                width: 8, height: 8,
                borderRadius: '50%',
                background: service.status === 'healthy' ? 'var(--color-success)' : service.status === 'warning' ? 'var(--color-warning)' : 'var(--color-error)',
                marginRight: 8,
              }} />
              <span style={{ flex: 1, font: 'var(--text-body-sm)' }}>{service.name}</span>
              <span style={{
                font: 'var(--text-caption)',
                color: 'var(--color-text-tertiary)',
              }}>{service.latency}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};
