'use client'

import { useEffect } from 'react'
import { Loader2, ShieldAlert } from 'lucide-react'
import { SettingsSaveBar, SettingsValidationSummary } from './components.js'
import { AccessProtectionCard } from './AccessProtectionCard.js'
import { AuthMfaCard } from './AuthMfaCard.js'
import { SecretsAuditCard } from './SecretsAuditCard.js'
import { SecurityStatusCard } from './SecurityStatusCard.js'
import { SessionPolicyCard } from './SessionPolicyCard.js'
import { useSecuritySettings } from './useSecuritySettings.js'

function CardSkeleton() {
  return (
    <div className="border-border bg-card animate-pulse rounded-lg border p-6">
      <div className="bg-muted mb-3 h-4 w-40 rounded" />
      <div className="bg-muted mb-4 h-3 w-72 rounded" />
      <div className="space-y-3">
        <div className="bg-muted h-3 w-full rounded" />
        <div className="bg-muted h-3 w-2/3 rounded" />
      </div>
    </div>
  )
}

export function SecurityTab({
  role,
  onNavigate,
}: {
  role?: string
  onNavigate?: (path: string) => void
}) {
  const canEdit = role === 'ADMIN'
  const {
    loading,
    loadError,
    data,
    form,
    setField,
    dirty,
    issues,
    hasErrors,
    saveState,
    save,
    reset,
    revokeState,
    revokeAllOtherSessions,
  } = useSecuritySettings(canEdit)

  // Deep-link support: /settings?tab=security&section=sessions|ip-allowlist|audit
  useEffect(() => {
    if (loading || typeof window === 'undefined') return
    const section = new URLSearchParams(window.location.search).get('section')
    if (!section) return
    const el = document.getElementById(`security-${section}`)
    el?.scrollIntoView({ behavior: 'smooth', block: 'start' })
  }, [loading])

  if (loading) {
    return (
      <div className="space-y-4">
        <CardSkeleton />
        <CardSkeleton />
        <CardSkeleton />
      </div>
    )
  }

  if (loadError || !data) {
    const forbidden = /forbidden|permission|insufficient/i.test(loadError ?? '')
    return (
      <div className="border-border bg-card text-muted-foreground flex items-start gap-3 rounded-lg border p-6 text-sm">
        <ShieldAlert size={20} className="text-warning mt-0.5 shrink-0" aria-hidden="true" />
        <div>
          <p className="text-foreground font-medium">
            {forbidden
              ? 'You do not have access to security settings'
              : 'Security settings unavailable'}
          </p>
          <p className="mt-1">
            {forbidden
              ? 'Ask an administrator to review the Security tab.'
              : (loadError ?? 'The security service could not be reached. Try again shortly.')}
          </p>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-4 pb-4">
      <SecurityStatusCard status={data.status} onNavigate={onNavigate} />

      {issues.length > 0 && <SettingsValidationSummary issues={issues} />}

      {!canEdit && (
        <p className="text-muted-foreground text-sm">
          You have read-only access. Only administrators can change security settings.
        </p>
      )}

      <AuthMfaCard
        form={form}
        setField={setField}
        canEdit={canEdit}
        viewerHasMfa={data.viewerHasMfa}
        withMfa={data.users.withMfa}
        totalAdmins={data.users.totalAdmins}
        onNavigate={onNavigate}
      />

      <div id="security-sessions">
        <SessionPolicyCard
          form={form}
          setField={setField}
          canEdit={canEdit}
          sessionMaxAgeHours={data.sessionMaxAgeHours}
          activeSessions={data.activeSessions}
          revokeState={revokeState}
          onRevokeAll={() => void revokeAllOtherSessions()}
        />
      </div>

      <div id="security-ip-allowlist">
        <AccessProtectionCard
          ipAllowlist={data.ipAllowlist}
          secrets={data.secrets}
          csrfEnabled={data.csrfEnabled}
          uploadValidation={data.uploadValidation}
          sources={data.sources}
          onNavigate={onNavigate}
        />
      </div>

      <div id="security-audit">
        <SecretsAuditCard
          secrets={data.secrets}
          auditEnabled={data.auditEnabled}
          failedLogins24h={data.failedLogins24h}
          users={data.users}
          apiKeys={data.apiKeys}
          sources={data.sources}
          onNavigate={onNavigate}
        />
      </div>

      {saveState === 'error' && (
        <p className="text-destructive text-sm" role="alert">
          Failed to save security settings. Please try again.
        </p>
      )}

      <SettingsSaveBar
        dirty={dirty}
        canEdit={canEdit}
        hasErrors={hasErrors}
        saveState={saveState}
        onSave={() => void save()}
        onReset={reset}
      />
    </div>
  )
}
