'use client'

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

function graceLabel(days: number): string {
  if (days === 0) return 'Immediately'
  if (days === 1) return '1 day'
  return `${days} days`
}

export function AuthMfaCard({
  form,
  setField,
  canEdit,
  viewerHasMfa,
  withMfa,
  totalAdmins,
  onNavigate,
}: {
  form: SecurityForm
  setField: <K extends keyof SecurityForm>(key: K, value: SecurityForm[K]) => void
  canEdit: boolean
  viewerHasMfa: boolean
  withMfa: number
  totalAdmins: number
  onNavigate?: (path: string) => void
}) {
  const headingId = useId()
  const graceId = useId()
  const [confirmEnable, setConfirmEnable] = useState(false)

  function requestMfaToggle(value: boolean) {
    if (value && !form.mfaRequired) {
      setConfirmEnable(true)
      return
    }
    setField('mfaRequired', value)
  }

  // Lockout-safe: the toggle can't be turned on until the acting admin has
  // their own MFA configured (the server enforces this too).
  const mfaToggleDisabled = !canEdit || (!form.mfaRequired && !viewerHasMfa)

  return (
    <SecurityCard
      headingId={headingId}
      title="Authentication & MFA"
      description="Require multi-factor authentication for admin accounts and control the enrollment window."
    >
      <div className="space-y-4">
        <SettingsToggleRow
          label="Require MFA for admin users"
          description="Admins must set up a TOTP authenticator app. Existing admins are prompted to enroll within the grace period."
          checked={form.mfaRequired}
          disabled={mfaToggleDisabled}
          onChange={requestMfaToggle}
        />

        <div className="flex items-center justify-between gap-4">
          <label htmlFor={graceId} className="flex-1">
            <span className="text-foreground text-base font-medium">Enrollment grace period</span>
            <p className="text-muted-foreground mt-0.5 text-sm">
              How long existing admins have to set up MFA before it is enforced.
            </p>
          </label>
          <select
            id={graceId}
            value={form.mfaGracePeriodDays}
            disabled={!canEdit || !form.mfaRequired}
            onChange={(e) => setField('mfaGracePeriodDays', 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"
          >
            {MFA_GRACE_PERIOD_OPTIONS.map((d) => (
              <option key={d} value={d}>
                {graceLabel(d)}
              </option>
            ))}
          </select>
        </div>
      </div>

      <div className="border-border mt-4 space-y-2 border-t pt-4">
        <StatusRow
          status={viewerHasMfa ? 'pass' : 'warning'}
          label="Your account"
          value={viewerHasMfa ? 'MFA enabled' : 'MFA not set up'}
        />
        {!viewerHasMfa && (
          <div className="space-y-2">
            <p className="text-muted-foreground text-sm">
              Set up MFA on your own account before requiring it for everyone, or you may lock
              yourself out.
            </p>
            {onNavigate && (
              <button
                type="button"
                onClick={() => onNavigate('/profile')}
                className="border-border text-foreground hover:bg-accent inline-flex items-center gap-2 rounded-md border px-3 py-1.5 text-sm transition-colors"
              >
                <ShieldCheck size={15} aria-hidden="true" />
                Set up MFA
              </button>
            )}
          </div>
        )}
        <StatusRow
          status={totalAdmins === 0 ? 'unknown' : withMfa === totalAdmins ? 'pass' : 'warning'}
          label="Admin MFA coverage"
          value={totalAdmins === 0 ? 'No admins' : `${withMfa} of ${totalAdmins} admins`}
        />
      </div>

      <ConfirmDangerousSettingDialog
        open={confirmEnable}
        title="Require MFA for all admin users?"
        description={`Admins without MFA will be prompted to enroll and must complete setup within the grace period (${graceLabel(
          form.mfaGracePeriodDays,
        )}). Make sure your own account has MFA configured first.`}
        confirmLabel="Require MFA"
        onConfirm={() => {
          setField('mfaRequired', true)
          setConfirmEnable(false)
        }}
        onCancel={() => setConfirmEnable(false)}
      />
    </SecurityCard>
  )
}
