'use client'

import { useId, useState } from 'react'
import { Check, X } from 'lucide-react'
import {
  validateIpRange,
  type IpAllowlistStatus,
  type SecretsStatus,
  type SecuritySourceMetadata,
} from '@actuate-media/cms-core/security-center'
import { SettingsSourceBadge } from './components.js'
import { SecurityCard, StatusRow } from './securityPrimitives.js'

export function AccessProtectionCard({
  ipAllowlist,
  secrets,
  csrfEnabled,
  uploadValidation,
  sources,
  onNavigate,
}: {
  ipAllowlist: IpAllowlistStatus
  secrets: SecretsStatus
  csrfEnabled: boolean
  uploadValidation: boolean
  sources: Record<string, SecuritySourceMetadata>
  onNavigate?: (path: string) => void
}) {
  const headingId = useId()
  const ipTestId = useId()
  const [ipTest, setIpTest] = useState('')
  const ipTestValid = ipTest.trim() === '' ? null : validateIpRange(ipTest)

  const distributed = secrets.rateLimitBackend === 'distributed'

  return (
    <SecurityCard
      headingId={headingId}
      title="Access & Request Protection"
      description="Network-level access restrictions and request-level protections. These are enforced by the platform; edit network rules in config."
    >
      {/* ── Access restrictions ─────────────────────────────────────────── */}
      <div className="space-y-2">
        <div className="flex items-center justify-between gap-2">
          <span className="text-foreground text-sm font-medium">Admin IP allowlist</span>
          <SettingsSourceBadge meta={sources.ipAllowlist} />
        </div>
        <StatusRow
          status={ipAllowlist.enabled ? 'pass' : 'unknown'}
          label="Status"
          value={ipAllowlist.enabled ? `${ipAllowlist.ranges.length} range(s)` : 'Not configured'}
        />
        {ipAllowlist.currentIp && (
          <StatusRow
            status={
              ipAllowlist.currentIpAllowed === null
                ? 'unknown'
                : ipAllowlist.currentIpAllowed
                  ? 'pass'
                  : 'fail'
            }
            label="Your current IP"
            value={
              <span className="font-mono text-xs">
                {ipAllowlist.currentIp}
                {ipAllowlist.currentIpAllowed === false && ' (blocked)'}
              </span>
            }
          />
        )}
        {ipAllowlist.enabled && (
          <div className="text-muted-foreground flex flex-wrap gap-1.5 pt-1">
            {ipAllowlist.ranges.map((r) => (
              <code key={r} className="bg-muted rounded px-1.5 py-0.5 font-mono text-xs">
                {r}
              </code>
            ))}
          </div>
        )}
        <div className="pt-1">
          <label htmlFor={ipTestId} className="text-muted-foreground mb-1 block text-sm">
            Validate an IP or CIDR range
          </label>
          <div className="flex items-center gap-2">
            <input
              id={ipTestId}
              type="text"
              value={ipTest}
              onChange={(e) => setIpTest(e.target.value)}
              placeholder="e.g. 203.0.113.0/24"
              className="border-border bg-input-background text-foreground focus-visible:ring-ring w-full max-w-xs rounded-md border px-3 py-1.5 font-mono text-sm focus-visible:ring-2 focus-visible:outline-none"
            />
            {ipTestValid === true && (
              <span className="text-success flex items-center gap-1 text-sm">
                <Check size={15} aria-hidden="true" /> Valid
              </span>
            )}
            {ipTestValid === false && (
              <span className="text-destructive flex items-center gap-1 text-sm">
                <X size={15} aria-hidden="true" /> Invalid
              </span>
            )}
          </div>
          <p className="text-muted-foreground mt-1 text-xs">
            Add validated ranges to <code className="font-mono">admin.ipAllowlist</code> in
            actuate.config.ts; the middleware enforces them.
          </p>
        </div>
      </div>

      {/* ── Request protection ──────────────────────────────────────────── */}
      <div className="border-border mt-4 space-y-2 border-t pt-4">
        <StatusRow
          status={csrfEnabled ? 'pass' : 'fail'}
          label="CSRF protection"
          value={csrfEnabled ? 'Enabled' : 'Disabled'}
          badge={<SettingsSourceBadge meta={sources.csrf} />}
        />
        <StatusRow
          status={distributed ? 'pass' : 'warning'}
          label="Rate limiting"
          value={distributed ? 'Distributed (Upstash)' : 'In-memory'}
          badge={<SettingsSourceBadge meta={sources.rateLimiting} />}
        />
        <StatusRow
          status={uploadValidation ? 'pass' : 'warning'}
          label="Upload validation"
          value="MIME + magic bytes + SVG sanitization"
          badge={<SettingsSourceBadge meta={sources.uploadValidation} />}
        />
        {onNavigate && (
          <button
            type="button"
            onClick={() => onNavigate('/media')}
            className="text-brand mt-1 text-sm hover:underline"
          >
            Manage upload rules in Media →
          </button>
        )}
      </div>
    </SecurityCard>
  )
}
