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

// ── Change username ────────────────────────────────────────────────────────
function ChangeUsername({ account, onChanged }) {
  const [username, setUsername] = useState(account.username)
  const [busy, setBusy] = useState(false)
  const [msg, setMsg] = useState('')
  const [error, setError] = useState('')

  async function save(e) {
    e.preventDefault()
    setMsg('')
    setError('')
    if (username.trim().length < 3) return setError('Username must be at least 3 characters.')
    setBusy(true)
    try {
      const { username: next } = await api.player.changeUsername(username.trim())
      setMsg('Username updated.')
      await onChanged(next)
    } catch (err) {
      if (err.status === 409) setError('That username is already taken.')
      else setError(err.message || 'Could not change your username.')
    } finally {
      setBusy(false)
    }
  }

  return (
    <Section title="Username">
      <form onSubmit={save} style={{ display: 'flex', flexDirection: 'column', gap: 12, maxWidth: 320 }}>
        <label>
          <span className="field-label">Username</span>
          <input type="text" value={username} onChange={(e) => setUsername(e.target.value)} className="input" autoComplete="username" />
        </label>
        <div>
          <button type="submit" disabled={busy || username.trim() === account.username} className="btn btn-primary btn-sq">
            {busy ? 'Saving…' : 'Change username'}
          </button>
        </div>
        <Note msg={msg} error={error} />
      </form>
    </Section>
  )
}

// ── Change / set password ──────────────────────────────────────────────────
function ChangePassword({ account }) {
  const hasPassword = account.has_password
  const [current, setCurrent] = useState('')
  const [next, setNext] = useState('')
  const [busy, setBusy] = useState(false)
  const [msg, setMsg] = useState('')
  const [error, setError] = useState('')

  async function save(e) {
    e.preventDefault()
    setMsg('')
    setError('')
    if (next.length < 8) return setError('New password must be at least 8 characters.')
    if (hasPassword && !current) return setError('Enter your current password.')
    setBusy(true)
    try {
      await api.player.changePassword(next, hasPassword ? current : undefined)
      setMsg(hasPassword ? 'Password changed.' : 'Password set. You can now sign in with it.')
      setCurrent('')
      setNext('')
    } catch (err) {
      setError(err.message || 'Could not change your password.')
    } finally {
      setBusy(false)
    }
  }

  let pwLabel = hasPassword ? 'Change password' : 'Set password'
  if (busy) pwLabel = 'Saving…'

  return (
    <Section title={hasPassword ? 'Password' : 'Set a password'}>
      {!hasPassword && (
        <p className="sans" style={{ marginTop: 0, color: 'var(--muted)', fontSize: '0.88rem', lineHeight: 1.6 }}>
          Your account was created through a linked provider and has no password yet. Set one to also be
          able to sign in with a username and password.
        </p>
      )}
      <form onSubmit={save} style={{ display: 'flex', flexDirection: 'column', gap: 12, maxWidth: 320 }}>
        {hasPassword && (
          <label>
            <span className="field-label">Current password</span>
            <input type="password" value={current} onChange={(e) => setCurrent(e.target.value)} className="input" autoComplete="current-password" />
          </label>
        )}
        <label>
          <span className="field-label">New password</span>
          <input type="password" value={next} onChange={(e) => setNext(e.target.value)} className="input" autoComplete="new-password" />
        </label>
        <div>
          <button type="submit" disabled={busy} className="btn btn-primary btn-sq">
            {pwLabel}
          </button>
        </div>
        <Note msg={msg} error={error} />
      </form>
    </Section>
  )
}

// ── Two-factor (TOTP) ──────────────────────────────────────────────────────
function TwoFactor({ account, reload }) {
  const enabled = account.totp_enabled
  const [setup, setSetup] = useState(null)
  const [code, setCode] = useState('')
  const [busy, setBusy] = useState(false)
  const [msg, setMsg] = useState('')
  const [error, setError] = useState('')
  const [newCodes, setNewCodes] = useState(null) // one-time recovery codes shown after enabling

  async function begin() {
    setBusy(true); setMsg(''); setError('')
    try {
      setSetup(await api.player.totpSetup())
      setCode('')
    } catch (err) {
      setError(err.message || 'Could not start setup.')
    } finally {
      setBusy(false)
    }
  }
  async function confirm() {
    setBusy(true); setMsg(''); setError('')
    try {
      const res = await api.player.totpEnable(code.trim())
      setSetup(null); setCode(''); setNewCodes(res?.recoveryCodes || null); setMsg('Two-factor is now enabled.')
      await reload()
    } catch (err) {
      setError(err.message || 'Could not enable two-factor.')
    } finally {
      setBusy(false)
    }
  }
  async function disable() {
    setBusy(true); setMsg(''); setError('')
    try {
      await api.player.totpDisable(code.trim())
      setCode(''); setMsg('Two-factor has been disabled.')
      await reload()
    } catch (err) {
      setError(err.message || 'Could not disable two-factor.')
    } finally {
      setBusy(false)
    }
  }

  return (
    <Section title="Two-factor authentication">
      <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: 18 }}>
        <span style={{ width: 9, height: 9, borderRadius: '50%', background: enabled ? '#7fd0a4' : 'var(--dim)' }} />
        {enabled ? 'Enabled' : 'Not enabled'}
      </div>

      {!enabled && !setup && (
        <div>
          <button onClick={begin} 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: 14 }}>
          <p className="sans" style={{ margin: 0, color: 'var(--muted)', fontSize: '0.88rem' }}>
            Scan this QR code with your authenticator app, then enter the current 6-digit code.
          </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={confirm} 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>
      )}

      {enabled && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <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>
      )}
      <Note msg={msg} error={error} />
      {newCodes && (
        <div style={{ marginTop: 16 }}>
          <RecoveryCodesDisplay codes={newCodes} onDone={() => setNewCodes(null)} />
        </div>
      )}
    </Section>
  )
}

// ── Linked SSO identities ──────────────────────────────────────────────────
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.player.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.player.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 (
    <Section title="Linked accounts">
      <p className="sans" style={{ marginTop: 0, color: 'var(--muted)', fontSize: '0.88rem', lineHeight: 1.6 }}>
        Link a Google, Discord, or other provider so you can sign in with it.
      </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?returnTo=${encodeURIComponent('/account')}`)} 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.</p>
      )}
    </Section>
  )
}

// ── Active mobile device sessions ──────────────────────────────────────────
function ActiveDevices() {
  const [sessions, setSessions] = useState(null)
  const [error, setError] = useState('')
  const [busyId, setBusyId] = useState(null)

  const load = useCallback(async () => {
    try {
      setSessions(await api.mySessions())
    } catch {
      setError('Could not load your devices.')
    }
  }, [])
  useEffect(() => { load() }, [load])

  async function revoke(id) {
    if (!window.confirm('Sign this device out? It will need to sign in again.')) return
    setBusyId(id)
    try {
      await api.revokeMySession(id)
      await load()
    } catch (err) {
      setError(err.message || 'Could not sign that device out.')
    } finally {
      setBusyId(null)
    }
  }

  const fmt = (d) => {
    const t = d ? new Date(d) : null
    return t && !Number.isNaN(t.getTime()) ? t.toLocaleString() : '—'
  }

  if (error) return (
    <Section title="Active devices"><ErrorState message={error} /></Section>
  )
  if (!sessions) return null

  return (
    <Section title="Active devices">
      <p className="sans" style={{ marginTop: 0, color: 'var(--muted)', fontSize: '0.88rem', lineHeight: 1.6 }}>
        Devices signed in to the mobile app. Sign one out to revoke its access — it may keep working for
        a few minutes until its current token expires.
      </p>
      {sessions.length === 0 ? (
        <p className="sans dim" style={{ fontSize: '0.86rem' }}>No mobile devices are signed in.</p>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, margin: '14px 0' }}>
          {sessions.map((s) => (
            <div key={s.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px', border: '1px solid var(--line)', borderRadius: 8 }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="sans" style={{ color: 'var(--head)', fontSize: '0.9rem' }}>
                  {s.deviceName || s.userAgent || 'Mobile device'}
                </div>
                <div className="sans dim" style={{ fontSize: '0.78rem' }}>Last active {fmt(s.lastUsedAt)}</div>
              </div>
              <button onClick={() => revoke(s.id)} disabled={busyId === s.id} className="pill" style={{ color: '#d98b84', borderColor: '#d98b84' }}>
                {busyId === s.id ? 'Signing out…' : 'Sign out'}
              </button>
            </div>
          ))}
        </div>
      )}
    </Section>
  )
}

// ── Shared bits ────────────────────────────────────────────────────────────
function Section({ title, children }) {
  return (
    <section style={{ borderTop: '1px solid var(--line-soft)', paddingTop: 26, marginTop: 26 }}>
      <h2 className="display" style={{ marginTop: 0, fontSize: '1.15rem', color: 'var(--head)' }}>{title}</h2>
      {children}
    </section>
  )
}
function Note({ msg, error }) {
  if (!msg && !error) return null
  return <p className="sans" style={{ margin: '4px 0 0', color: error ? '#d98b84' : '#7fd0a4', fontSize: '0.85rem' }}>{error || msg}</p>
}

// ── Page ───────────────────────────────────────────────────────────────────
export default function PlayerAccount() {
  const { refresh } = useAuth()
  const [account, setAccount] = useState(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  const load = useCallback(async () => {
    try {
      setAccount(await api.player.getAccount())
    } catch {
      setError('Could not load your account.')
    } finally {
      setLoading(false)
    }
  }, [])
  useEffect(() => { load() }, [load])

  // After a username change: reload local account + refresh the auth context so
  // the header reflects the new name.
  const onUsernameChanged = useCallback(async () => {
    await Promise.all([load(), refresh()])
  }, [load, refresh])

  return (
    <div>
      {loading && <Loading />}
      {error && <ErrorState message={error} />}
      {!loading && !error && account && (
        <>
          <p className="sans" style={{ margin: 0, color: 'var(--muted)', fontSize: '0.9rem' }}>
            Signed in as <strong style={{ color: 'var(--head)' }}>{account.username}</strong>
            {account.email ? ` · ${account.email}` : ''}
          </p>
          <ChangeUsername account={account} onChanged={onUsernameChanged} />
          <ChangePassword account={account} />
          <TwoFactor account={account} reload={load} />
          {account.totp_enabled && (
            <>
              <TrustedDevicesPanel />
              <RecoveryCodesPanel hasPassword={account.has_password !== false} />
            </>
          )}
          <LinkedAccounts />
          <ActiveDevices />
        </>
      )}
    </div>
  )
}
