'use client'

import { useId, useState } from 'react'
import { Loader2 } from 'lucide-react'
import { MAX_CONCURRENT_SESSION_OPTIONS } from '@actuate-media/cms-core/security-center'
import { ConfirmDangerousSettingDialog } from './components.js'
import { SecurityCard, StatusRow } from './securityPrimitives.js'
import type { SecurityForm } from './useSecuritySettings.js'

function sessionsLabel(n: number): string {
  return n === 0 ? 'Unlimited' : String(n)
}

export function SessionPolicyCard({
  form,
  setField,
  canEdit,
  sessionMaxAgeHours,
  activeSessions,
  revokeState,
  onRevokeAll,
}: {
  form: SecurityForm
  setField: <K extends keyof SecurityForm>(key: K, value: SecurityForm[K]) => void
  canEdit: boolean
  sessionMaxAgeHours: number
  activeSessions: number
  revokeState: 'idle' | 'working' | 'done' | 'error'
  onRevokeAll: () => void
}) {
  const headingId = useId()
  const maxId = useId()
  const [confirmRevoke, setConfirmRevoke] = useState(false)

  const maxAgeDays = Math.round(sessionMaxAgeHours / 24)

  return (
    <SecurityCard
      headingId={headingId}
      title="Session Policy"
      description="Control how many sessions an account can hold and revoke active sessions."
    >
      <div className="space-y-4">
        <div className="flex items-center justify-between gap-4">
          <label htmlFor={maxId} className="flex-1">
            <span className="text-foreground text-base font-medium">
              Maximum concurrent sessions
            </span>
            <p className="text-muted-foreground mt-0.5 text-sm">
              Oldest sessions are signed out when a user exceeds this. Choose Unlimited to disable
              the cap.
            </p>
          </label>
          <select
            id={maxId}
            value={form.maxConcurrentSessions}
            disabled={!canEdit}
            onChange={(e) => setField('maxConcurrentSessions', Number(e.target.value))}
            className="border-border bg-input-background text-foreground focus-visible:ring-ring rounded-md border px-3 py-2 text-sm focus-visible:ring-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
          >
            {MAX_CONCURRENT_SESSION_OPTIONS.map((n) => (
              <option key={n} value={n}>
                {sessionsLabel(n)}
              </option>
            ))}
          </select>
        </div>
      </div>

      <div className="border-border mt-4 space-y-2 border-t pt-4">
        <StatusRow status="pass" label="Active admin sessions" value={String(activeSessions)} />
        <StatusRow
          status="pass"
          label="Maximum session age"
          value={`${maxAgeDays} day${maxAgeDays === 1 ? '' : 's'}`}
        />
        <StatusRow status="pass" label="Revoke sessions on password change" value="Enabled" />
      </div>

      <div className="border-border mt-4 flex items-center justify-between gap-3 border-t pt-4">
        <div>
          <p className="text-foreground text-sm font-medium">Revoke other sessions</p>
          <p className="text-muted-foreground text-sm">
            Sign out every session except this one. Useful after a suspected compromise.
          </p>
          {revokeState === 'done' && (
            <p className="text-success mt-1 text-sm" aria-live="polite">
              Other sessions revoked.
            </p>
          )}
          {revokeState === 'error' && (
            <p className="text-destructive mt-1 text-sm" aria-live="polite">
              Could not revoke sessions. Try again.
            </p>
          )}
        </div>
        <button
          type="button"
          disabled={!canEdit || revokeState === 'working'}
          onClick={() => setConfirmRevoke(true)}
          className="border-border text-foreground hover:bg-accent inline-flex shrink-0 items-center gap-2 rounded-md border px-3 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50"
        >
          {revokeState === 'working' && (
            <Loader2 size={15} className="animate-spin" aria-hidden="true" />
          )}
          Revoke other sessions
        </button>
      </div>

      <ConfirmDangerousSettingDialog
        open={confirmRevoke}
        title="Revoke all other sessions?"
        description="Every active session except your current one will be signed out immediately. Those users (and your other devices) will need to sign in again."
        confirmLabel="Revoke sessions"
        onConfirm={() => {
          setConfirmRevoke(false)
          onRevokeAll()
        }}
        onCancel={() => setConfirmRevoke(false)}
      />
    </SecurityCard>
  )
}
