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

/**
 * PrekeyStock — gauge showing one-time prekey count + signed prekey info.
 */
export function PrekeyStock({ lowThreshold = 5 }: { lowThreshold?: number }): React.ReactElement {
  const { state } = useShadeState();
  const { theme } = useShadeContext();

  const remaining = state?.prekeys.oneTimeRemaining ?? 0;
  const isLow = remaining < lowThreshold;
  const color = isLow ? theme.warning : theme.success;

  return (
    <WidgetShell title="Prekey stock">
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 12 }}>
        <div style={{ fontSize: 36, fontWeight: 700, color, fontFamily: theme.fontMono, lineHeight: 1 }}>
          {remaining}
        </div>
        <div style={{ fontSize: 12, color: theme.textMuted }}>one-time prekeys</div>
      </div>
      {isLow && (
        <div
          style={{
            fontSize: 11,
            color: theme.warning,
            background: 'rgba(234, 179, 8, 0.1)',
            border: `1px solid ${theme.warning}`,
            borderRadius: 4,
            padding: '6px 8px',
            marginBottom: 12,
          }}
        >
          Low — replenish recommended (threshold: {lowThreshold})
        </div>
      )}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 11, color: theme.textMuted }}>
        {state?.prekeys.signedPreKeyId != null && (
          <div>
            <span style={{ color: theme.textDim }}>Signed prekey ID</span>{' '}
            <span style={{ fontFamily: theme.fontMono, color: theme.text }}>
              {state.prekeys.signedPreKeyId}
            </span>
          </div>
        )}
        {state?.prekeys.lastGenerated && (
          <div>
            <span style={{ color: theme.textDim }}>Last generated</span>{' '}
            {formatRelative(state.prekeys.lastGenerated)}
          </div>
        )}
        {state?.prekeys.lastConsumed && (
          <div>
            <span style={{ color: theme.textDim }}>Last consumed</span>{' '}
            {formatRelative(state.prekeys.lastConsumed)}
          </div>
        )}
      </div>
    </WidgetShell>
  );
}
