import { useState } from 'react'
import { Modal } from '@/components/common/Modal'
import { cn } from '@/lib/utils'

interface RevokeSessionsModalProps {
  isOpen: boolean
  onClose: () => void
  onConfirm: () => Promise<void>
  scope: 'all' | 'others'
  activeUserCount: number
}

/**
 * Confirmation modal for bulk session revocation. Two scopes:
 *
 * - "others" — revokes other users' sessions, caller stays signed in.
 * - "all" — revokes everyone including the caller; the parent handles
 *   the post-revoke auto-redirect to /login (see plan §4.8 D4).
 */
export function RevokeSessionsModal({
  isOpen,
  onClose,
  onConfirm,
  scope,
  activeUserCount,
}: RevokeSessionsModalProps) {
  const [busy, setBusy] = useState(false)

  const isAll = scope === 'all'
  const otherCount = isAll ? activeUserCount : Math.max(activeUserCount - 1, 0)

  const title = isAll ? 'Sign out everyone?' : 'Sign out other users?'
  const body = isAll
    ? `This signs out all ${activeUserCount} active users including yourself. Everyone will need to sign in again.`
    : `This signs out the ${otherCount} other active users in your account. They'll need to sign in again. You stay signed in.`
  const confirmLabel = isAll
    ? 'Sign out everyone'
    : otherCount === 1
      ? 'Sign out 1 user'
      : `Sign out ${otherCount} users`

  const handleConfirm = async () => {
    setBusy(true)
    try {
      await onConfirm()
    } finally {
      setBusy(false)
    }
  }

  return (
    <Modal
      isOpen={isOpen}
      onClose={busy ? () => undefined : onClose}
      title={title}
      size="sm"
      footer={
        <div className="flex justify-end gap-2">
          <button
            type="button"
            onClick={onClose}
            disabled={busy}
            className={cn(
              'rounded-md border px-4 py-2 text-sm font-medium',
              'border-border text-foreground hover:bg-card-hover',
              'disabled:opacity-50',
            )}
          >
            Cancel
          </button>
          <button
            type="button"
            onClick={handleConfirm}
            disabled={busy}
            className={cn(
              'rounded-md border px-4 py-2 text-sm font-medium',
              'border-danger/40 bg-danger/10 text-danger hover:bg-danger/15',
              'disabled:opacity-50',
            )}
          >
            {busy ? 'Working…' : confirmLabel}
          </button>
        </div>
      }
    >
      <p className="text-sm text-foreground">{body}</p>
    </Modal>
  )
}
