'use client';

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

/**
 * D7. 系统管理
 *
 * 管理员账号（RBAC）、系统配置、合约管理、系统监控
 */

interface Admin {
  account: string;
  name: string;
  role: string;
  lastLogin: string;
  active: boolean;
}

interface ConfigSection {
  title: string;
  items: { label: string; value: string }[];
}

interface ServiceHealth {
  name: string;
  status: string;
  cpu: string;
  mem: string;
}

interface SystemHealthResponse {
  services: ServiceHealth[];
  contracts: { name: string; address: string; version: string; status: string }[];
}

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

export const SystemManagementPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState<'admins' | 'config' | 'contracts' | 'monitor'>('admins');

  const { data: adminsData, isLoading: adminsLoading } = useApi<Admin[]>(
    activeTab === 'admins' ? '/api/v1/admin/system/admins' : null,
  );
  const { data: configData, isLoading: configLoading } = useApi<ConfigSection[]>(
    activeTab === 'config' ? '/api/v1/admin/system/config' : null,
  );
  const { data: healthData, isLoading: healthLoading } = useApi<SystemHealthResponse>(
    activeTab === 'contracts' || activeTab === 'monitor' ? '/api/v1/admin/system/health' : null,
  );

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

      {/* Tabs */}
      <div style={{ display: 'flex', gap: 4, marginBottom: 20, borderBottom: '1px solid var(--color-border-light)' }}>
        {[
          { key: 'admins', label: t('system_tab_admins') },
          { key: 'config', label: t('system_tab_config') },
          { key: 'contracts', label: t('system_tab_contracts') },
          { key: 'monitor', label: t('system_tab_monitor') },
        ].map(tab => (
          <button
            key={tab.key}
            onClick={() => setActiveTab(tab.key as typeof activeTab)}
            style={{
              padding: '10px 16px',
              border: 'none',
              borderBottom: activeTab === tab.key ? '2px solid var(--color-primary)' : '2px solid transparent',
              background: 'none',
              color: activeTab === tab.key ? 'var(--color-primary)' : 'var(--color-text-tertiary)',
              cursor: 'pointer',
              font: 'var(--text-label)',
            }}
          >{tab.label}</button>
        ))}
      </div>

      {/* Admin Accounts */}
      {activeTab === 'admins' && (
        <div style={{
          background: 'var(--color-surface)',
          borderRadius: 'var(--radius-md)',
          border: '1px solid var(--color-border-light)',
          overflow: 'hidden',
        }}>
          <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--color-border-light)', display: 'flex', justifyContent: 'space-between' }}>
            <span style={{ font: 'var(--text-h3)' }}>{t('system_admin_list')}</span>
            <button style={{
              padding: '6px 14px', border: 'none', borderRadius: 'var(--radius-sm)',
              background: 'var(--color-primary)', color: 'white', cursor: 'pointer', font: 'var(--text-label-sm)',
            }}>{t('system_add_admin')}</button>
          </div>
          {adminsLoading ? (
            <div style={loadingBox}>Loading...</div>
          ) : (
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr style={{ background: 'var(--color-gray-50)' }}>
                  {[t('system_th_account'), t('system_th_name'), t('system_th_role'), t('system_th_last_login'), t('system_th_status'), 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>
                {(adminsData ?? []).map(admin => (
                  <tr key={admin.account} style={{ borderBottom: '1px solid var(--color-border-light)' }}>
                    <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px' }}>{admin.account}</td>
                    <td style={{ font: 'var(--text-label-sm)', padding: '10px 14px' }}>{admin.name}</td>
                    <td style={{ padding: '10px 14px' }}>
                      <span style={{
                        padding: '2px 8px', borderRadius: 'var(--radius-full)',
                        background: 'var(--color-primary-surface)', color: 'var(--color-primary)',
                        font: 'var(--text-caption)', fontWeight: 500,
                      }}>{admin.role}</span>
                    </td>
                    <td style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)', padding: '10px 14px' }}>{admin.lastLogin}</td>
                    <td style={{ padding: '10px 14px' }}>
                      <span style={{
                        width: 8, height: 8, borderRadius: '50%', display: 'inline-block',
                        background: admin.active ? 'var(--color-success)' : 'var(--color-text-disabled)',
                      }} />
                    </td>
                    <td style={{ padding: '10px 14px' }}>
                      <button style={{ padding: '4px 10px', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-sm)', background: 'none', cursor: 'pointer', font: 'var(--text-caption)' }}>{t('edit')}</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      )}

      {/* System Config */}
      {activeTab === 'config' && (
        configLoading ? (
          <div style={loadingBox}>Loading...</div>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 16 }}>
            {(configData ?? []).map(section => (
              <div key={section.title} 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', marginBottom: 16 }}>
                  <span style={{ font: 'var(--text-h3)' }}>{section.title}</span>
                  <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-primary)',
                  }}>{t('edit')}</button>
                </div>
                {section.items.map((item, i) => (
                  <div key={item.label} style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    padding: '10px 0',
                    borderTop: i > 0 ? '1px solid var(--color-border-light)' : 'none',
                  }}>
                    <span style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-secondary)' }}>{item.label}</span>
                    <span style={{ font: 'var(--text-label-sm)', color: 'var(--color-primary)' }}>{item.value}</span>
                  </div>
                ))}
              </div>
            ))}
          </div>
        )
      )}

      {/* Contract Management */}
      {activeTab === 'contracts' && (
        <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('system_contract_status')}</div>
          {healthLoading ? (
            <div style={loadingBox}>Loading...</div>
          ) : (healthData?.contracts ?? []).map(c => (
            <div key={c.name} style={{
              display: 'flex', alignItems: 'center', padding: '14px 0',
              borderBottom: '1px solid var(--color-border-light)',
            }}>
              <div style={{ flex: 1 }}>
                <div style={{ font: 'var(--text-label)' }}>{c.name}</div>
                <div style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)', fontFamily: 'var(--font-family-mono)' }}>{c.address}</div>
              </div>
              <span style={{ font: 'var(--text-caption)', color: 'var(--color-text-tertiary)', marginRight: 16 }}>{c.version}</span>
              <span style={{
                padding: '2px 8px', borderRadius: 'var(--radius-full)',
                background: 'var(--color-success-light)', color: 'var(--color-success)',
                font: 'var(--text-caption)',
              }}>{c.status}</span>
            </div>
          ))}
        </div>
      )}

      {/* System Monitor */}
      {activeTab === 'monitor' && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 16 }}>
          {/* Service 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('system_health_check')}</div>
            {healthLoading ? (
              <div style={loadingBox}>Loading...</div>
            ) : (healthData?.services ?? []).map(s => (
              <div key={s.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: s.status === 'healthy' ? 'var(--color-success)' : 'var(--color-warning)', marginRight: 10 }} />
                <span style={{ flex: 1, font: 'var(--text-body-sm)' }}>{s.name}</span>
                <span style={{ font: 'var(--text-caption)', color: 'var(--color-text-tertiary)', marginRight: 16 }}>CPU {s.cpu}</span>
                <span style={{ font: 'var(--text-caption)', color: 'var(--color-text-tertiary)' }}>MEM {s.mem}</span>
              </div>
            ))}
          </div>

          {/* API Response Time */}
          <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('system_api_response')}</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)',
            }}>
              P50 / P95 / P99 延迟趋势图
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
