'use client';

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

/**
 * D4. 链上监控 - 合约状态与链上数据
 *
 * 合约状态、铸造/销毁记录、Gas费监控、链上异常检测
 * 注：此页面仅对平台管理员可见，发行方/消费者不可见
 */

interface ChainMonitorData {
  contracts: { label: string; status: string; txCount: string; lastBlock: string }[];
  events: { event: string; detail: string; hash: string; time: string; type: string }[];
  gasMonitor: { current: string; average: string; todaySpend: string };
}

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

const eventColors: Record<string, string> = {
  mint: 'var(--color-success)',
  transfer: 'var(--color-info)',
  redeem: 'var(--color-primary)',
  burn: 'var(--color-error)',
};

export const ChainMonitorPage: React.FC = () => {
  const { data, isLoading, error } = useApi<ChainMonitorData>('/api/v1/admin/chain/contracts');

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

  const contractStats = data?.contracts ?? [];
  const recentEvents = data?.events ?? [];
  const gasMonitor = data?.gasMonitor ?? { current: '-', average: '-', todaySpend: '-' };

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

      {/* Contract Status */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }}>
        {contractStats.map(c => (
          <div key={c.label} style={{
            background: 'var(--color-surface)', borderRadius: 'var(--radius-md)',
            border: '1px solid var(--color-border-light)', padding: 16,
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
              <span style={{ font: 'var(--text-label)', color: 'var(--color-text-primary)' }}>{c.label}</span>
              <span style={{
                padding: '2px 8px', borderRadius: 'var(--radius-full)', font: 'var(--text-caption)',
                background: c.status === 'Active' ? 'var(--color-success-light)' : 'var(--color-error-light)',
                color: c.status === 'Active' ? 'var(--color-success)' : 'var(--color-error)',
                fontWeight: 600,
              }}>{c.status}</span>
            </div>
            <div style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)' }}>TX: {c.txCount} · Block: {c.lastBlock}</div>
          </div>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
        {/* Chain Events */}
        <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('chain_recent_events')}</h2>
          {recentEvents.map((e, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', padding: '10px 0', borderBottom: '1px solid var(--color-border-light)' }}>
              <div style={{
                width: 8, height: 8, borderRadius: '50%', background: eventColors[e.type] ?? 'var(--color-gray-400)', marginRight: 12,
              }} />
              <div style={{ flex: 1 }}>
                <div style={{ font: 'var(--text-label)', color: 'var(--color-text-primary)' }}>{e.event}</div>
                <div style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)' }}>{e.detail}</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ font: 'var(--text-caption)', fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-link)' }}>{e.hash}</div>
                <div style={{ font: 'var(--text-caption)', color: 'var(--color-text-tertiary)' }}>{e.time}</div>
              </div>
            </div>
          ))}
        </div>

        {/* Gas Monitor */}
        <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('chain_gas_monitor')}</h2>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12, marginBottom: 16 }}>
            {[
              { label: t('chain_current_gas'), value: gasMonitor.current, color: 'var(--color-success)' },
              { label: t('chain_today_avg'), value: gasMonitor.average, color: 'var(--color-info)' },
              { label: t('chain_today_gas_spend'), value: gasMonitor.todaySpend, color: 'var(--color-warning)' },
            ].map(g => (
              <div key={g.label} style={{ textAlign: 'center', padding: 12, background: 'var(--color-gray-50)', borderRadius: 'var(--radius-sm)' }}>
                <div style={{ font: 'var(--text-h3)', color: g.color }}>{g.value}</div>
                <div style={{ font: 'var(--text-caption)', color: 'var(--color-text-tertiary)' }}>{g.label}</div>
              </div>
            ))}
          </div>
          <div style={{
            height: 160, background: 'var(--color-gray-50)', borderRadius: 'var(--radius-sm)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: 'var(--color-text-tertiary)', font: 'var(--text-body)',
          }}>Gas费24小时趋势图</div>
        </div>
      </div>
    </div>
  );
};
