import { useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { confirmUserEmailChange } from '../../api/session'

/**
 * Landing page for the link sent to the new address after requesting an email change
 * from account settings (`requestUserEmailChange`).
 */
export function ConfirmEmailChangePage() {
  const [searchParams] = useSearchParams()
  const token = searchParams.get('token') ?? ''
  const [phase, setPhase] = useState<'loading' | 'ok' | 'err'>(token ? 'loading' : 'err')
  const [message, setMessage] = useState(token ? '' : 'Missing confirmation token. Open the link from your email.')

  useEffect(() => {
    if (!token) return
    let cancelled = false
    void confirmUserEmailChange(token)
      .then((res) => {
        if (cancelled) return
        setPhase('ok')
        const m = typeof res?.message === 'string' && res.message.trim() ? res.message.trim() : ''
        setMessage(m || 'Your email address has been updated. You can close this tab or sign in again.')
      })
      .catch((e) => {
        if (cancelled) return
        setPhase('err')
        setMessage(e instanceof Error ? e.message : 'Confirmation failed.')
      })
    return () => {
      cancelled = true
    }
  }, [token])

  return (
    <div className="registration-form container mt-5 mb-5 text-center">
      <div className="text-center mb-4">
        <Link to="/">
          <img
            src="/alrahma_logo.png"
            alt=""
            style={{ width: 180, height: 120, objectFit: 'contain' }}
            onError={(ev) => {
              ;(ev.target as HTMLImageElement).style.display = 'none'
            }}
          />
        </Link>
      </div>
      {phase === 'loading' ? (
        <>
          <h3 className="h5 text-muted">Confirming your new email…</h3>
          <p className="text-muted small">Please wait.</p>
        </>
      ) : null}
      {phase === 'ok' ? (
        <>
          <h3 className="text-success h4">Email confirmed</h3>
          <p className="text-muted">{message}</p>
          <Link className="btn btn-success mt-2" to="/login">
            Sign in
          </Link>
        </>
      ) : null}
      {phase === 'err' ? (
        <>
          <h3 className="text-danger h4">Could not confirm email</h3>
          <p className="text-muted">{message}</p>
          <Link className="btn btn-outline-secondary mt-2" to="/login">
            Sign in
          </Link>
        </>
      ) : null}
    </div>
  )
}
