'use client';

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

/**
 * 做市商管理仪表盘
 *
 * 做市商列表、流动性池、订单簿深度、市场健康指标、风险预警
 */

interface MarketMakerData {
  stats: { label: string; value: string; change: string; trend: 'up' | 'down'; color: string; invertTrend?: boolean }[];
  marketMakers: { name: string; status: 'active' | 'paused' | 'suspended'; tvl: string; spread: string; volume: string; pnl: string }[];
  liquidityPools: { category: string; tvl: string; percent: number; makers: number; color: string }[];
  healthIndicators: { name: string; value: string; target: string; status: 'good' | 'warning' }[];
  riskAlerts: { time: string; maker: string; type: string; desc: string; severity: 'high' | 'medium' | 'low' }[];
}

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

const getStatusConfig = (status: string) => {
  const map: Record<string, { bg: string; color: string; label: () => string }> = {
    active: { bg: 'var(--color-success-light)', color: 'var(--color-success)', label: () => t('mm_status_active') },
    paused: { bg: 'var(--color-warning-light)', color: 'var(--color-warning)', label: () => t('mm_status_paused') },
    suspended: { bg: 'var(--color-error-light)', color: 'var(--color-error)', label: () => t('mm_status_suspended') },
  };
  return map[status] ?? { bg: 'var(--color-gray-100)', color: 'var(--color-text-tertiary)', label: () => status };
};

const getSeverityConfig = (severity: string) => {
  const map: Record<string, { bg: string; color: string; label: () => string }> = {
    high: { bg: 'var(--color-error-light)', color: 'var(--color-error)', label: () => t('severity_high') },
    medium: { bg: 'var(--color-warning-light)', color: 'var(--color-warning)', label: () => t('severity_medium') },
    low: { bg: 'var(--color-info-light)', color: 'var(--color-info)', label: () => t('severity_low') },
  };
  return map[severity] ?? { bg: 'var(--color-gray-100)', color: 'var(--color-text-tertiary)', label: () => severity };
};

export const MarketMakerPage: React.FC = () => {
  const { data, isLoading, error } = useApi<MarketMakerData>('/api/v1/admin/mm/list');

  const suspendMutation = useApiMutation('PATCH', '/api/v1/admin/mm/suspend', { invalidateKeys: ['/api/v1/admin/mm/list'] });
  const resumeMutation = useApiMutation('PATCH', '/api/v1/admin/mm/resume', { invalidateKeys: ['/api/v1/admin/mm/list'] });

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

  const stats = data?.stats ?? [];
  const marketMakers = data?.marketMakers ?? [];
  const liquidityPools = data?.liquidityPools ?? [];
  const healthIndicators = data?.healthIndicators ?? [];
  const riskAlerts = data?.riskAlerts ?? [];

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

      {/* Stats Grid */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }}>
        {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.invertTrend
                ? (stat.trend === 'up' ? 'var(--color-error)' : 'var(--color-success)')
                : (stat.trend === 'up' ? 'var(--color-success)' : 'var(--color-error)'),
              marginTop: 4,
            }}>
              {stat.change}
            </div>
          </div>
        ))}
      </div>

      {/* Market Maker Table */}
      <div style={{
        background: 'var(--color-surface)',
        borderRadius: 'var(--radius-md)',
        border: '1px solid var(--color-border-light)',
        overflow: 'hidden',
        marginBottom: 24,
      }}>
        <div style={{ padding: '16px 20px', font: 'var(--text-h3)', borderBottom: '1px solid var(--color-border-light)' }}>
          {t('market_maker_list')}
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ background: 'var(--color-gray-50)' }}>
              {[t('mm_th_name'), t('mm_th_status'), 'TVL', t('market_maker_spread'), t('mm_th_daily_volume'), t('market_maker_pnl'), 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>
            {marketMakers.map(mm => {
              const s = getStatusConfig(mm.status);
              return (
                <tr key={mm.name} style={{ borderBottom: '1px solid var(--color-border-light)' }}>
                  <td style={{ font: 'var(--text-label-sm)', padding: '10px 14px' }}>{mm.name}</td>
                  <td style={{ padding: '10px 14px' }}>
                    <span style={{
                      padding: '2px 8px',
                      borderRadius: 'var(--radius-full)',
                      background: s.bg,
                      color: s.color,
                      font: 'var(--text-caption)',
                    }}>{s.label()}</span>
                  </td>
                  <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px' }}>{mm.tvl}</td>
                  <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px' }}>{mm.spread}</td>
                  <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px' }}>{mm.volume}</td>
                  <td style={{
                    font: 'var(--text-label-sm)',
                    padding: '10px 14px',
                    color: mm.pnl.startsWith('+') ? 'var(--color-success)' : 'var(--color-error)',
                  }}>{mm.pnl}</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('details')}</button>
                    {mm.status === 'active' && (
                      <button onClick={() => suspendMutation.mutate({ name: mm.name })} style={{ padding: '4px 10px', border: 'none', borderRadius: 'var(--radius-sm)', background: 'var(--color-warning)', cursor: 'pointer', font: 'var(--text-caption)', color: 'white' }}>{t('suspend')}</button>
                    )}
                    {mm.status === 'paused' && (
                      <button onClick={() => resumeMutation.mutate({ name: mm.name })} style={{ padding: '4px 10px', border: 'none', borderRadius: 'var(--radius-sm)', background: 'var(--color-success)', cursor: 'pointer', font: 'var(--text-caption)', color: 'white' }}>{t('resume')}</button>
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* Liquidity Pools + Order Book Depth */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 24 }}>
        {/* Liquidity Pool Distribution */}
        <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('mm_liquidity_pools')}</div>
          {liquidityPools.map(pool => (
            <div key={pool.category} style={{ marginBottom: 14 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                <span style={{ font: 'var(--text-label-sm)', color: 'var(--color-text-primary)' }}>
                  {pool.category}
                  <span style={{ font: 'var(--text-caption)', color: 'var(--color-text-tertiary)', marginLeft: 8 }}>
                    {pool.makers} {t('mm_unit_makers')}
                  </span>
                </span>
                <span style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)' }}>
                  {pool.tvl} ({pool.percent}%)
                </span>
              </div>
              <div style={{
                width: '100%', height: 8,
                background: 'var(--color-gray-100)',
                borderRadius: 4,
                overflow: 'hidden',
              }}>
                <div style={{
                  width: `${pool.percent}%`,
                  height: '100%',
                  background: pool.color,
                  borderRadius: 4,
                }} />
              </div>
            </div>
          ))}
        </div>

        {/* Order Book Depth */}
        <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('mm_order_book_depth')}</div>
          <div style={{
            height: 260,
            background: 'var(--color-gray-50)',
            borderRadius: 'var(--radius-sm)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: 'var(--color-text-tertiary)',
          }}>
            Recharts 面积图 (Bid/Ask 深度分布)
          </div>
        </div>
      </div>

      {/* Market Health + Risk Alerts */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        {/* Market Health Indicators */}
        <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('mm_health_indicators')}</div>
          {healthIndicators.map(ind => (
            <div key={ind.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: ind.status === 'good' ? 'var(--color-success)' : 'var(--color-warning)',
                marginRight: 10,
                flexShrink: 0,
              }} />
              <span style={{ flex: 1, font: 'var(--text-body-sm)' }}>{ind.name}</span>
              <span style={{
                font: 'var(--text-label-sm)',
                color: ind.status === 'good' ? 'var(--color-success)' : 'var(--color-warning)',
                marginRight: 12,
              }}>{ind.value}</span>
              <span style={{
                font: 'var(--text-caption)',
                color: 'var(--color-text-tertiary)',
              }}>{ind.target}</span>
            </div>
          ))}
        </div>

        {/* Risk Alerts */}
        <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('mm_risk_alerts')}</div>
            <span style={{
              padding: '2px 8px',
              borderRadius: 'var(--radius-full)',
              background: 'var(--color-error-light)',
              color: 'var(--color-error)',
              font: 'var(--text-caption)',
            }}>
              {riskAlerts.filter(a => a.severity === 'high').length} {t('mm_high_risk')}
            </span>
          </div>
          {riskAlerts.map((alert, i) => {
            const sev = getSeverityConfig(alert.severity);
            return (
              <div key={i} style={{
                padding: 12,
                background: 'var(--color-gray-50)',
                borderRadius: 'var(--radius-sm)',
                marginBottom: i < riskAlerts.length - 1 ? 8 : 0,
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{
                      padding: '2px 6px',
                      borderRadius: 'var(--radius-full)',
                      background: sev.bg,
                      color: sev.color,
                      font: 'var(--text-caption)',
                    }}>{sev.label()}</span>
                    <span style={{ font: 'var(--text-label-sm)' }}>{alert.maker}</span>
                    <span style={{ font: 'var(--text-caption)', color: 'var(--color-text-tertiary)' }}>{alert.type}</span>
                  </div>
                  <span style={{ font: 'var(--text-caption)', color: 'var(--color-text-tertiary)' }}>{alert.time}</span>
                </div>
                <div style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-secondary)' }}>
                  {alert.desc}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};
