'use client';

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

/**
 * D5. 风控中心
 *
 * 风险仪表盘、可疑交易、黑名单管理、OFAC筛查日志
 */

interface RiskDashboard {
  riskEvents: number;
  suspiciousTrades: number;
  frozenAccounts: number;
  ofacHits: number;
}

interface RiskAlert {
  message: string;
}

interface SuspiciousTrade {
  id: string;
  user: string;
  type: string;
  amount: number;
  time: string;
  score: number;
}

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

export const RiskCenterPage: React.FC = () => {
  const { data: dashboardData, isLoading: dashLoading, error: dashError } = useApi<RiskDashboard>('/api/v1/admin/risk/dashboard');
  const { data: alertsData, isLoading: alertsLoading } = useApi<RiskAlert[]>('/api/v1/admin/risk/alerts');
  const { data: tradesData, isLoading: tradesLoading } = useApi<SuspiciousTrade[]>('/api/v1/admin/risk/suspicious-trades');

  const freezeMutation = useApiMutation<void>('POST', '', {
    invalidateKeys: ['/api/v1/admin/risk/suspicious-trades'],
  });

  const riskStats = dashboardData ? [
    { label: t('risk_events'), value: String(dashboardData.riskEvents), color: 'var(--color-error)', bg: 'var(--color-error-light)' },
    { label: t('risk_suspicious_trades'), value: String(dashboardData.suspiciousTrades), color: 'var(--color-warning)', bg: 'var(--color-warning-light)' },
    { label: t('risk_frozen_accounts'), value: String(dashboardData.frozenAccounts), color: 'var(--color-info)', bg: 'var(--color-info-light)' },
    { label: t('risk_ofac_hits'), value: String(dashboardData.ofacHits), color: 'var(--color-success)', bg: 'var(--color-success-light)' },
  ] : [];

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

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <h1 style={{ font: 'var(--text-h1)' }}>{t('risk_title')}</h1>
        <button style={{
          padding: '8px 16px',
          border: '1px solid var(--color-primary)',
          borderRadius: 'var(--radius-full)',
          background: 'var(--color-primary-surface)',
          color: 'var(--color-primary)',
          cursor: 'pointer',
          font: 'var(--text-label-sm)',
        }}>
          ✨ {t('risk_ai_warning')}
        </button>
      </div>

      {/* Risk Stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }}>
        {dashLoading ? (
          <div style={{ ...loadingBox, gridColumn: '1 / -1' }}>Loading...</div>
        ) : riskStats.map(s => (
          <div key={s.label} style={{
            background: s.bg,
            borderRadius: 'var(--radius-md)',
            padding: 16,
          }}>
            <div style={{ font: 'var(--text-body-sm)', color: s.color, opacity: 0.8 }}>{s.label}</div>
            <div style={{ font: 'var(--text-h1)', color: s.color, marginTop: 4 }}>{s.value}</div>
          </div>
        ))}
      </div>

      {/* AI Risk Alerts */}
      <div style={{
        background: 'var(--color-primary-surface)',
        borderRadius: 'var(--radius-md)',
        border: '1px solid var(--color-primary)22',
        padding: 16,
        marginBottom: 24,
      }}>
        <div style={{ font: 'var(--text-label)', color: 'var(--color-primary)', marginBottom: 12 }}>
          🤖 {t('risk_ai_warning')}
        </div>
        {alertsLoading ? (
          <div style={loadingBox}>Loading...</div>
        ) : (alertsData ?? []).map((alert, i) => (
          <div key={i} style={{
            padding: 12,
            background: 'var(--color-surface)',
            borderRadius: 'var(--radius-sm)',
            font: 'var(--text-body-sm)',
            marginBottom: i < (alertsData?.length ?? 0) - 1 ? 8 : 0,
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}>
            <span>{alert.message}</span>
            <button style={{
              padding: '4px 12px',
              border: 'none',
              borderRadius: 'var(--radius-sm)',
              background: 'var(--color-primary)',
              color: 'white',
              cursor: 'pointer',
              font: 'var(--text-caption)',
              whiteSpace: 'nowrap',
              marginLeft: 12,
            }}>{t('process')}</button>
          </div>
        ))}
      </div>

      {/* Suspicious Transactions Table */}
      <div style={{
        background: 'var(--color-surface)',
        borderRadius: 'var(--radius-md)',
        border: '1px solid var(--color-border-light)',
        overflow: 'hidden',
      }}>
        <div style={{ padding: '16px 20px', font: 'var(--text-h3)', borderBottom: '1px solid var(--color-border-light)' }}>
          {t('risk_suspicious_trades')}
        </div>
        {tradesLoading ? (
          <div style={loadingBox}>Loading...</div>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ background: 'var(--color-gray-50)' }}>
                {[t('risk_th_trade_id'), t('risk_th_user'), t('risk_th_anomaly_type'), t('risk_th_amount'), t('risk_th_time'), t('risk_th_risk_score'), t('actions')].map(h => (
                  <th key={h} style={{
                    font: 'var(--text-label-sm)',
                    color: 'var(--color-text-tertiary)',
                    padding: '10px 14px',
                    textAlign: 'left',
                  }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {(tradesData ?? []).map(tx => (
                <tr key={tx.id} style={{ borderBottom: '1px solid var(--color-border-light)' }}>
                  <td style={{ font: 'var(--text-body-sm)', fontFamily: 'var(--font-family-mono)', padding: '10px 14px' }}>{tx.id}</td>
                  <td style={{ font: 'var(--text-label-sm)', padding: '10px 14px' }}>{tx.user}</td>
                  <td style={{ padding: '10px 14px' }}>
                    <span style={{
                      padding: '2px 8px',
                      borderRadius: 'var(--radius-full)',
                      background: 'var(--color-warning-light)',
                      color: 'var(--color-warning)',
                      font: 'var(--text-caption)',
                    }}>{tx.type}</span>
                  </td>
                  <td style={{ font: 'var(--text-label-sm)', color: 'var(--color-error)', padding: '10px 14px' }}>${tx.amount?.toLocaleString()}</td>
                  <td style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)', padding: '10px 14px' }}>{tx.time}</td>
                  <td style={{ padding: '10px 14px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <div style={{
                        width: 60, height: 6,
                        background: 'var(--color-gray-100)',
                        borderRadius: 3,
                        overflow: 'hidden',
                      }}>
                        <div style={{
                          width: `${tx.score}%`,
                          height: '100%',
                          background: tx.score >= 80 ? 'var(--color-error)' : tx.score >= 60 ? 'var(--color-warning)' : 'var(--color-info)',
                          borderRadius: 3,
                        }} />
                      </div>
                      <span style={{ font: 'var(--text-caption)', color: tx.score >= 80 ? 'var(--color-error)' : 'var(--color-warning)' }}>
                        {tx.score}
                      </span>
                    </div>
                  </td>
                  <td style={{ padding: '10px 14px', display: 'flex', gap: 4 }}>
                    <button style={{ padding: '4px 10px', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-sm)', background: 'none', cursor: 'pointer', font: 'var(--text-caption)', color: 'var(--color-text-secondary)' }}>{t('mark')}</button>
                    <button
                      onClick={() => freezeMutation.mutate({ userId: tx.user })}
                      style={{ padding: '4px 10px', border: 'none', borderRadius: 'var(--radius-sm)', background: 'var(--color-error)', cursor: 'pointer', font: 'var(--text-caption)', color: 'white' }}>{t('user_freeze')}</button>
                    <button style={{ padding: '4px 10px', border: 'none', borderRadius: 'var(--radius-sm)', background: 'var(--color-warning)', cursor: 'pointer', font: 'var(--text-caption)', color: 'white' }}>SAR</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
};
