import { useCallback, useEffect, useState } from 'react'
import { Loading, ErrorState } from '../../../components/PageState.jsx'
import ProviderIcon from '../../../components/ProviderIcon.jsx'
import RecoveryCodesDisplay from '../../../components/security/RecoveryCodesDisplay.jsx'
import TrustedDevicesPanel from '../../../components/security/TrustedDevicesPanel.jsx'
import RecoveryCodesPanel from '../../../components/security/RecoveryCodesPanel.jsx'
import { api } from '../../../api/client.js'

// Link/unlink external SSO identities to this account. Linking redirects through
// the provider's OAuth flow (/auth/sso/:id/link) and returns here with ?linked
// or ?link_error. Only providers that are enabled + valid can be linked.
function LinkedAccounts() {
  const [linked, setLinked] = useState(null)
  const [available, setAvailable] = useState([])
  const [error, setError] = useState('')

  const banner = (() => {
    const q = new URLSearchParams(window.location.search)
    if (q.get('linked')) return { ok: true, text: 'Account linked.' }
    if (q.get('link_error') === 'in_use') return { ok: false, text: 'That external account is already linked to another user.' }
    if (q.get('link_error')) return { ok: false, text: 'Could not link that account. Please try again.' }
    return null
  })()

  const load = useCallback(async () => {
    try {
      const [ids, avail] = await Promise.all([
        api.admin.linkedIdentities(),
        api.authProviders().catch(() => []),
      ])
      setLinked(ids)
      setAvailable(Array.isArray(avail) ? avail : [])
    } catch {
      setError('Could not load linked accounts.')
    }
  }, [])
  useEffect(() => {
    load()
  }, [load])

  const nameFor = (id) => available.find((p) => p.id === id)?.name || id.charAt(0).toUpperCase() + id.slice(1)
  const iconFor = (id) => (id === 'google' || id === 'discord' ? id : 'oidc')

  async function unlink(provider) {
    if (!window.confirm(`Unlink ${nameFor(provider)} from your account?`)) return
    try {
      await api.admin.unlinkIdentity(provider)
      await load()
    } catch (err) {
      setError(err.message || 'Could not unlink.')
    }
  }

  if (error) return <ErrorState message={error} />
  if (!linked) return null

  const linkedIds = new Set(linked.map((i) => i.provider))
  const linkable = available.filter((p) => !linkedIds.has(p.id))

  return (
    <div style={{ marginTop: 40, borderTop: '1px solid var(--line-soft)', paddingTop: 28 }}>
      <h2 className="display" style={{ marginTop: 0, fontSize: '1.2rem', color: 'var(--head)' }}>
        Linked accounts
      </h2>
      <p className="sans" style={{ color: 'var(--muted)', fontSize: '0.9rem', lineHeight: 1.6 }}>
        Link a Google, Discord, or other SSO account so you can sign in with it. SSO can only sign in
        to an account it is linked to — linking here is what grants that access.
      </p>

      {banner && (
        <p className="sans" style={{ color: banner.ok ? '#7fd0a4' : '#d98b84', fontSize: '0.86rem' }}>
          {banner.text}
        </p>
      )}

      {linked.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, margin: '14px 0' }}>
          {linked.map((i) => (
            <div key={i.provider} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px', border: '1px solid var(--line)', borderRadius: 8 }}>
              <span style={{ display: 'inline-flex', width: 20, height: 20 }}>
                <ProviderIcon icon={iconFor(i.provider)} size={20} />
              </span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="sans" style={{ color: 'var(--head)', fontSize: '0.9rem' }}>{nameFor(i.provider)}</div>
                {i.email && <div className="sans dim" style={{ fontSize: '0.78rem' }}>{i.email}</div>}
              </div>
              <button onClick={() => unlink(i.provider)} className="pill" style={{ color: '#d98b84', borderColor: '#d98b84' }}>
                Unlink
              </button>
            </div>
          ))}
        </div>
      )}

      {linkable.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 6 }}>
          {linkable.map((p) => (
            <button
              key={p.id}
              onClick={() => window.location.assign(`/api/v1/auth/sso/${p.id}/link`)}
              className="btn"
              style={{ display: 'flex', alignItems: 'center', gap: 10, justifyContent: 'center', width: '100%', maxWidth: 320, borderRadius: 8, padding: 10, border: '1px solid var(--line)', background: 'rgba(255,255,255,0.04)', color: 'var(--ink)' }}
            >
              <span style={{ display: 'inline-flex', width: 18, height: 18 }}>
                <ProviderIcon icon={p.icon} size={18} />
              </span>
              Link {p.name}
            </button>
          ))}
        </div>
      )}

      {linked.length === 0 && linkable.length === 0 && (
        <p className="sans dim" style={{ fontSize: '0.86rem' }}>
          No SSO providers are enabled. Configure them under <strong>Authentication</strong>.
        </p>
      )}
    </div>
  )
}

// Self-service account security: enable / disable optional TOTP two-factor.
export default function AccountAdmin() {
  const [account, setAccount] = useState(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  // Enrollment state.
  const [setup, setSetup] = useState(null) // fields qr and otpauthUrl once enrolling
  const [code, setCode] = useState('')
  const [busy, setBusy] = useState(false)
  const [msg, setMsg] = useState('')
  const [newCodes, setNewCodes] = useState(null) // one-time recovery codes shown after enabling

  async function load() {
    try {
      setAccount(await api.admin.getAccount())
    } catch {
      setError('Could not load your account.')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    load()
  }, [])

  if (loading) return <Loading />
  if (error) return <ErrorState message={error} />

  async function beginSetup() {
    setBusy(true)
    setMsg('')
    setError('')
    try {
      setSetup(await api.admin.totpSetup())
      setCode('')
    } catch (err) {
      setError(err.message || 'Could not start setup.')
    } finally {
      setBusy(false)
    }
  }

  async function confirmEnable() {
    setBusy(true)
    setMsg('')
    setError('')
    try {
      const res = await api.admin.totpEnable(code.trim())
      setSetup(null)
      setCode('')
      setNewCodes(res?.recoveryCodes || null)
      setMsg('Two-factor authentication is now enabled.')
      await load()
    } catch (err) {
      setError(err.message || 'Could not enable two-factor.')
    } finally {
      setBusy(false)
    }
  }

  async function disable() {
    setBusy(true)
    setMsg('')
    setError('')
    try {
      await api.admin.totpDisable(code.trim())
      setCode('')
      setMsg('Two-factor authentication has been disabled.')
      await load()
    } catch (err) {
      setError(err.message || 'Could not disable two-factor.')
    } finally {
      setBusy(false)
    }
  }

  const enabled = account?.totp_enabled

  return (
    <section style={{ maxWidth: 560 }}>
      <h2 className="display" style={{ marginTop: 0, fontSize: '1.2rem', color: 'var(--head)' }}>
        Two-factor authentication
      </h2>
      <p className="sans" style={{ color: 'var(--muted)', fontSize: '0.9rem', lineHeight: 1.6 }}>
        Add a time-based one-time code (TOTP) from an authenticator app as a second step at login.
        Optional, and only affects your own account.
      </p>

      <div
        className="sans"
        style={{
          display: 'inline-flex',
          alignItems: 'center',
          gap: 8,
          padding: '6px 12px',
          borderRadius: 999,
          border: '1px solid var(--line)',
          fontSize: '0.82rem',
          color: enabled ? '#7fd0a4' : 'var(--muted)',
          marginBottom: 22,
        }}
      >
        <span
          style={{
            width: 9,
            height: 9,
            borderRadius: '50%',
            background: enabled ? '#7fd0a4' : 'var(--dim)',
          }}
        />
        {enabled ? 'Enabled' : 'Not enabled'}
      </div>

      {/* Enable flow */}
      {!enabled && !setup && (
        <div>
          <button onClick={beginSetup} disabled={busy} className="btn btn-primary btn-sq">
            {busy ? 'Preparing…' : 'Set up two-factor'}
          </button>
        </div>
      )}

      {!enabled && setup && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <p className="sans" style={{ margin: 0, color: 'var(--muted)', fontSize: '0.88rem' }}>
            1. Scan this QR code with your authenticator app, then enter the current 6-digit code to confirm.
          </p>
          <img
            src={setup.qr}
            alt="TOTP QR code"
            width={180}
            height={180}
            style={{ borderRadius: 8, background: '#fff', padding: 8, alignSelf: 'flex-start' }}
          />
          <label style={{ display: 'block', maxWidth: 220 }}>
            <span className="field-label">Verification code</span>
            <input
              type="text"
              inputMode="numeric"
              autoComplete="one-time-code"
              placeholder="6-digit code"
              value={code}
              onChange={(e) => setCode(e.target.value)}
              className="input"
            />
          </label>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
            <button onClick={confirmEnable} disabled={busy || !code.trim()} className="btn btn-primary btn-sq">
              {busy ? 'Enabling…' : 'Confirm & enable'}
            </button>
            <button onClick={() => setSetup(null)} disabled={busy} className="pill">
              Cancel
            </button>
          </div>
        </div>
      )}

      {/* Disable flow */}
      {enabled && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <p className="sans" style={{ margin: 0, color: 'var(--muted)', fontSize: '0.88rem' }}>
            Enter a current code from your authenticator to turn two-factor off.
          </p>
          <label style={{ display: 'block', maxWidth: 220 }}>
            <span className="field-label">Verification code</span>
            <input
              type="text"
              inputMode="numeric"
              autoComplete="one-time-code"
              placeholder="6-digit code"
              value={code}
              onChange={(e) => setCode(e.target.value)}
              className="input"
            />
          </label>
          <div>
            <button onClick={disable} disabled={busy || !code.trim()} className="btn btn-sq" style={{ borderColor: '#d98b84', color: '#d98b84' }}>
              {busy ? 'Disabling…' : 'Disable two-factor'}
            </button>
          </div>
        </div>
      )}

      {msg && <p className="sans" style={{ marginTop: 16, color: '#7fd0a4', fontSize: '0.86rem' }}>{msg}</p>}
      {error && <p className="sans" style={{ marginTop: 16, color: '#d98b84', fontSize: '0.86rem' }}>{error}</p>}

      {/* One-time recovery codes shown right after enabling 2FA. */}
      {newCodes && (
        <div style={{ marginTop: 20 }}>
          <RecoveryCodesDisplay codes={newCodes} onDone={() => setNewCodes(null)} />
        </div>
      )}

      {/* Trusted devices + recovery-code management, only relevant with 2FA on. */}
      {enabled && (
        <>
          <TrustedDevicesPanel />
          <RecoveryCodesPanel hasPassword={account?.has_password !== false} />
        </>
      )}

      <LinkedAccounts />
    </section>
  )
}
