// Reset password — URL `/reset?token=…`. The link the reset email points at.
// Reads the single-use token from the URL and POSTs it with the new password to
// /auth/password-reset/confirm. On success the api invalidates the token and the
// user signs in with the new password.
import type { ReactNode } from 'react'
import { useState, type FormEvent } from 'react'
import type { PageMeta } from '@voltro/web'
import { T, useT } from '@voltro/i18n'
import { AuthShell } from '../../components/AuthShell'
import { PasswordStrength } from '../../components/PasswordStrength'
import { postAuth } from '../../lib/auth'
import { tokenFromLocation } from '../../lib/redirect'
import { getCatalog } from '../../locales'

export const renderMode = 'static' as const

export const meta = ({ locale }: { readonly locale: string }): PageMeta => ({
  title: getCatalog(locale)['meta.reset.title'],
})

export default function Reset(): ReactNode {
  const [password, setPassword] = useState('')
  const [pending, setPending] = useState(false)
  const [failed, setFailed] = useState(false)
  const [done, setDone] = useState(false)
  const passwordLabel = useT('auth.newPassword')

  const onSubmit = (e: FormEvent): void => {
    e.preventDefault()
    const token = tokenFromLocation()
    if (!token) { setFailed(true); return }
    setPending(true)
    setFailed(false)
    void postAuth('/auth/password-reset/confirm', { token, password })
      .then((res) => {
        if (res.ok) setDone(true)
        else setFailed(true)
        setPending(false)
      })
      .catch(() => { setFailed(true); setPending(false) })
  }

  return (
    <AuthShell titleId="reset.title" footer={<a href="/login"><T id="reset.toLogin" /></a>}>
      {done ? (
        <p className="ok" role="status"><T id="reset.done" /></p>
      ) : (
        <form className="auth-form" onSubmit={onSubmit}>
          <p className="muted"><T id="reset.body" /></p>
          <label>
            <span><T id="auth.newPassword" /></span>
            <input type="password" required minLength={8} aria-label={passwordLabel} value={password} onChange={(e) => setPassword(e.target.value)} />
          </label>
          <PasswordStrength value={password} />
          {failed ? <p className="error-text"><T id="reset.failed" /></p> : null}
          <button type="submit" className="btn" disabled={pending}>
            <T id={pending ? 'auth.pending' : 'reset.submit'} />
          </button>
        </form>
      )}
    </AuthShell>
  )
}
