import { type FormEvent, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { submitPasswordReset } from '../../api/passwordFlow'
import { STRONG_PASSWORD_REGEX } from './passwordValidation'

function togglePw(id: string, iconEl: HTMLElement) {
  const input = document.getElementById(id) as HTMLInputElement | null
  const icon = iconEl.querySelector('i')
  if (!input || !icon) return
  if (input.type === 'password') {
    input.type = 'text'
    icon.classList.remove('fa-eye')
    icon.classList.add('fa-eye-slash')
  } else {
    input.type = 'password'
    icon.classList.remove('fa-eye-slash')
    icon.classList.add('fa-eye')
  }
}

/** CI `user/reset_password.php` — token from email link. */
export function ResetPasswordPage() {
  const [searchParams] = useSearchParams()
  const token = searchParams.get('token') ?? ''
  const [password, setPassword] = useState('')
  const [confirm, setConfirm] = useState('')
  const [pwErr, setPwErr] = useState(false)
  const [matchErr, setMatchErr] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [done, setDone] = useState(false)

  async function onSubmit(e: FormEvent) {
    e.preventDefault()
    const okPw = STRONG_PASSWORD_REGEX.test(password)
    const okMatch = password === confirm
    setPwErr(!okPw)
    setMatchErr(!okMatch)
    if (!okPw || !okMatch || !token) return
    try {
      await submitPasswordReset({ token, password, pass_confirm: confirm })
      setDone(true)
      setError(null)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Reset failed.')
    }
  }

  if (!token) {
    return (
      <div className="registration-form container mt-5 mb-5 text-center">
        <div className="alert alert-warning">Missing reset token. Open the link from your email.</div>
        <Link to="/forgot-password">Request a new link</Link>
      </div>
    )
  }

  if (done) {
    return (
      <div className="registration-form container mt-5 mb-5 text-center">
        <h3 className="text-success">Password updated</h3>
        <p>You can sign in with your new password.</p>
        <Link className="btn btn-success" to="/login">
          Login
        </Link>
      </div>
    )
  }

  return (
    <div className="registration-form container mt-5 mb-5 text-center">
      <form onSubmit={(e) => void onSubmit(e)} className="text-start" style={{ maxWidth: 480, margin: '0 auto' }}>
        <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>
        <h3 className="text-center text-success mb-4" style={{ fontFamily: 'Arial, sans-serif' }}>
          Reset Your Password
        </h3>
        {error ? <div className="alert alert-danger">{error}</div> : null}

        <div className="form-group position-relative mb-4">
          <input
            type="password"
            className="form-control pe-5"
            id="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            placeholder="Enter new password"
            maxLength={30}
            required
            autoComplete="new-password"
          />
          <span
            className="position-absolute top-50 end-0 translate-middle-y me-3"
            style={{ cursor: 'pointer' }}
            onClick={(e) => togglePw('password', e.currentTarget)}
            aria-hidden
          >
            <i className="fa-solid fa-eye" />
          </span>
          <small className={`text-danger ${pwErr ? '' : 'd-none'}`}>
            Password must be at least 8 characters, include uppercase, lowercase, number, and special character.
          </small>
        </div>

        <div className="form-group position-relative mb-4">
          <input
            type="password"
            className="form-control pe-5"
            id="password_confirm"
            value={confirm}
            onChange={(e) => setConfirm(e.target.value)}
            placeholder="Confirm new password"
            maxLength={30}
            required
            autoComplete="new-password"
          />
          <span
            className="position-absolute top-50 end-0 translate-middle-y me-3"
            style={{ cursor: 'pointer' }}
            onClick={(e) => togglePw('password_confirm', e.currentTarget)}
            aria-hidden
          >
            <i className="fa-solid fa-eye" />
          </span>
          <small className={`text-danger ${matchErr ? '' : 'd-none'}`}>Passwords do not match.</small>
        </div>

        <div className="d-grid mb-3">
          <button type="submit" className="btn btn-success">
            Reset Password
          </button>
        </div>
      </form>
    </div>
  )
}
