import React from 'react';
import { useShadeState } from '../useShadeState.js';
import { useShadeContext } from '../ShadeProvider.js';
import { WidgetShell } from './shared.js';

/**
 * ServerStatus — prekey server stats: registered identities, fetches, etc.
 */
export function ServerStatus(): React.ReactElement {
  const { state } = useShadeState();
  const { theme } = useShadeContext();

  const stats = state?.server;

  return (
    <WidgetShell title="Prekey server">
      {!stats ? (
        <div style={{ color: theme.textMuted, fontSize: 13 }}>Loading…</div>
      ) : (
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: '1fr 1fr',
            gap: 12,
          }}
        >
          <Stat label="Registered" value={stats.registeredIdentities.length} theme={theme} />
          <Stat label="Bundle fetches" value={stats.totalBundleFetches} theme={theme} />
          <Stat label="Replenishes" value={stats.totalReplenishes} theme={theme} />
          <Stat
            label="Rate limited"
            value={stats.totalRateLimited}
            theme={theme}
            {...(stats.totalRateLimited > 0 ? { color: theme.danger } : {})}
          />
        </div>
      )}
    </WidgetShell>
  );
}

function Stat({
  label,
  value,
  theme,
  color,
}: {
  label: string;
  value: number;
  theme: any;
  color?: string;
}): React.ReactElement {
  return (
    <div
      style={{
        padding: 10,
        background: theme.bg,
        border: `1px solid ${theme.border}`,
        borderRadius: 6,
      }}
    >
      <div style={{ fontSize: 10, color: theme.textDim, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
        {label}
      </div>
      <div
        style={{
          fontSize: 22,
          fontWeight: 700,
          color: color ?? theme.text,
          fontFamily: theme.fontMono,
          marginTop: 2,
          lineHeight: 1.1,
        }}
      >
        {value.toLocaleString()}
      </div>
    </div>
  );
}
