'use client'

import { useId } from 'react'
import type {
  ApiKeysSecuritySummary,
  CheckStatus,
  SecretsStatus,
  SecuritySourceMetadata,
  UsersSecuritySummary,
} from '@actuate-media/cms-core/security-center'
import { SettingsSourceBadge } from './components.js'
import { SecurityCard, StatusRow } from './securityPrimitives.js'

function secretValue(status: CheckStatus): string {
  switch (status) {
    case 'pass':
      return 'Configured'
    case 'warning':
      return 'Not configured'
    case 'fail':
      return 'Missing / invalid'
    default:
      return 'Unknown'
  }
}

export function SecretsAuditCard({
  secrets,
  auditEnabled,
  failedLogins24h,
  users,
  apiKeys,
  sources,
  onNavigate,
}: {
  secrets: SecretsStatus
  auditEnabled: boolean
  failedLogins24h: number
  users: UsersSecuritySummary
  apiKeys: ApiKeysSecuritySummary
  sources: Record<string, SecuritySourceMetadata>
  onNavigate?: (path: string) => void
}) {
  const headingId = useId()

  return (
    <SecurityCard
      headingId={headingId}
      title="Secrets, Encryption & Audit"
      description="Platform secret status (values are never shown), audit logging, and cross-module risk."
    >
      <div className="space-y-2">
        <StatusRow
          status={secrets.cmsSecret}
          label="CMS signing secret"
          value={secretValue(secrets.cmsSecret)}
          badge={<SettingsSourceBadge meta={sources.cmsSecret} />}
        />
        <StatusRow
          status={secrets.encryptionKey}
          label="Encryption key"
          value={secretValue(secrets.encryptionKey)}
          badge={<SettingsSourceBadge meta={sources.encryptionKey} />}
        />
        <StatusRow status="pass" label="API keys hashed at rest" value="Yes" />
        <StatusRow
          status={secrets.webhookSecretsEncrypted ? 'pass' : 'warning'}
          label="Webhook secrets encrypted"
          value={secrets.webhookSecretsEncrypted ? 'Yes' : 'Plaintext fallback'}
        />
      </div>

      <div className="border-border mt-4 space-y-2 border-t pt-4">
        <StatusRow
          status={auditEnabled ? 'pass' : 'warning'}
          label="Audit logging"
          value={auditEnabled ? 'Enabled' : 'Disabled'}
          badge={<SettingsSourceBadge meta={sources.audit} />}
        />
        <StatusRow
          status={failedLogins24h >= 20 ? 'warning' : 'pass'}
          label="Failed logins (24h)"
          value={String(failedLogins24h)}
        />
      </div>

      {/* Cross-module summaries — link out, never duplicate management here. */}
      <div className="border-border mt-4 space-y-3 border-t pt-4">
        <div className="flex items-start justify-between gap-3">
          <div className="text-sm">
            <p className="text-foreground font-medium">Users</p>
            <p className="text-muted-foreground">
              {users.totalAdmins} admin{users.totalAdmins === 1 ? '' : 's'},{' '}
              {users.adminsWithoutMfa} without MFA
              {users.inactive > 0 ? `, ${users.inactive} inactive` : ''}
            </p>
          </div>
          {onNavigate && (
            <button
              type="button"
              onClick={() => onNavigate('/settings?tab=users')}
              className="text-brand shrink-0 text-sm hover:underline"
            >
              Review users →
            </button>
          )}
        </div>
        <div className="flex items-start justify-between gap-3">
          <div className="text-sm">
            <p className="text-foreground font-medium">API keys</p>
            <p className="text-muted-foreground">
              {apiKeys.active} active, {apiKeys.broadScope} broad-scope, {apiKeys.withoutExpiration}{' '}
              without expiry
            </p>
          </div>
          {onNavigate && (
            <button
              type="button"
              onClick={() => onNavigate('/settings?tab=api-keys')}
              className="text-brand shrink-0 text-sm hover:underline"
            >
              Review API keys →
            </button>
          )}
        </div>
      </div>
    </SecurityCard>
  )
}
