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

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

/** CI `user/set_authorized_user_password.php` — path includes user id; token in query or hidden. */
export function SetAuthorizedUserPasswordPage() {
  const { userId: userIdParam } = useParams()
  const [searchParams] = useSearchParams()
  const navigate = useNavigate()
  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)

  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 || !userIdParam || !token) return
    try {
      await submitAuthorizedUserPassword(userIdParam, {
        token,
        password,
        password_confirm: confirm,
      })
      navigate('/user/password-set-success', { replace: true })
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unable to save password.')
    }
  }

  if (!userIdParam || !token) {
    return (
      <div className="container py-5 text-center">
        <div className="alert alert-warning">Invalid or expired link.</div>
        <Link to="/login">Login</Link>
      </div>
    )
  }

  return (
    <div className="registration-form container mt-5 mb-5">
      <form onSubmit={(e) => void onSubmit(e)} autoComplete="off">
        <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' }}>
          Create Your Password
        </h3>
        {error ? <div className="alert alert-danger">{error}</div> : null}

        <input type="hidden" name="user_id" value={userIdParam} readOnly />
        <input type="hidden" name="token" value={token} readOnly />

        <div className="mb-3 position-relative">
          <input
            type="password"
            className="form-control pe-5"
            id="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            placeholder="Enter new password"
            maxLength={40}
            required
            autoComplete="new-password"
            onCopy={(e) => e.preventDefault()}
            onCut={(e) => e.preventDefault()}
            onPaste={(e) => e.preventDefault()}
          />
          <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 meet complexity requirements (see CI rules).
          </small>
        </div>

        <div className="mb-3 position-relative">
          <input
            type="password"
            className="form-control pe-5"
            id="password_confirm"
            value={confirm}
            onChange={(e) => setConfirm(e.target.value)}
            placeholder="Confirm new password"
            maxLength={40}
            required
            autoComplete="new-password"
            onCopy={(e) => e.preventDefault()}
            onCut={(e) => e.preventDefault()}
            onPaste={(e) => e.preventDefault()}
          />
          <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">
          <button type="submit" className="btn btn-success">
            Save Password
          </button>
        </div>
      </form>
    </div>
  )
}
