import { useEffect, useState, type FormEvent } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import {
  fetchRegisterCaptcha,
  fetchSchoolPolicyHtml,
  submitFullRegistration,
  type FullRegisterPayload,
} from '../api/registerFull'
import { NE_STATES } from '../data/neStates'

function formatUsPhone(input: string): string {
  const raw = input.replace(/\D/g, '').slice(0, 10)
  if (raw.length <= 3) return raw
  if (raw.length <= 6) return `${raw.slice(0, 3)}-${raw.slice(3)}`
  return `${raw.slice(0, 3)}-${raw.slice(3, 6)}-${raw.slice(6)}`
}

export function RegisterPage() {
  const navigate = useNavigate()

  const [captchaChallenge, setCaptchaChallenge] = useState('')
  const [captchaLoading, setCaptchaLoading] = useState(true)

  const [firstname, setFirstname] = useState('')
  const [lastname, setLastname] = useState('')
  const [gender, setGender] = useState('')
  const [cellphone, setCellphone] = useState('')
  const [email, setEmail] = useState('')
  const [confirmEmail, setConfirmEmail] = useState('')
  const [addressStreet, setAddressStreet] = useState('')
  const [apt, setApt] = useState('')
  const [city, setCity] = useState('')
  const [state, setState] = useState('')
  const [zip, setZip] = useState('')

  const [isParent, setIsParent] = useState(false)
  const [noSecondParentInfo, setNoSecondParentInfo] = useState(false)
  const [secondFirstname, setSecondFirstname] = useState('')
  const [secondLastname, setSecondLastname] = useState('')
  const [secondGender, setSecondGender] = useState('')
  const [secondEmail, setSecondEmail] = useState('')
  const [secondCellphone, setSecondCellphone] = useState('')

  const [acceptPolicy, setAcceptPolicy] = useState(false)
  const [captchaAnswer, setCaptchaAnswer] = useState('')

  const [policyHtml, setPolicyHtml] = useState<string | null>(null)
  const [policyLoading, setPolicyLoading] = useState(false)

  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [fieldErrors, setFieldErrors] = useState<Record<string, string[]>>({})

  async function loadCaptcha() {
    setCaptchaLoading(true)
    try {
      const { challenge } = await fetchRegisterCaptcha()
      setCaptchaChallenge(challenge)
      setCaptchaAnswer('')
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Could not load CAPTCHA.')
    } finally {
      setCaptchaLoading(false)
    }
  }

  useEffect(() => {
    void loadCaptcha()
  }, [])

  async function openPolicyModal() {
    if (!policyHtml) {
      setPolicyLoading(true)
      try {
        const html = await fetchSchoolPolicyHtml()
        setPolicyHtml(html)
      } catch {
        setPolicyHtml('<p>Unable to load policy.</p>')
      } finally {
        setPolicyLoading(false)
      }
    }
    const el = document.getElementById('policyModal')
    const B = (
      window as unknown as {
        bootstrap?: { Modal: { getOrCreateInstance: (n: HTMLElement) => { show: () => void } } }
      }
    ).bootstrap
    if (el && B?.Modal) {
      B.Modal.getOrCreateInstance(el).show()
    }
  }

  function fieldErr(key: string): string | undefined {
    return fieldErrors[key]?.[0]
  }

  async function onSubmit(e: FormEvent) {
    e.preventDefault()
    setError(null)
    setFieldErrors({})

    if (email.trim() !== confirmEmail.trim()) {
      setError('Email and confirm email must match.')
      return
    }
    if (!acceptPolicy) {
      setError('You must accept the school policies.')
      return
    }
    const zipOk = /^\d{5}$/.test(zip.trim())
    if (!zipOk) {
      setError('Zip must be exactly 5 digits.')
      return
    }
    const phoneDigits = cellphone.replace(/\D/g, '')
    if (phoneDigits.length !== 10) {
      setError('Please enter a valid 10-digit cell phone number.')
      return
    }

    if (isParent && !noSecondParentInfo) {
      const sd = secondCellphone.replace(/\D/g, '')
      if (sd.length !== 10) {
        setError('Second parent phone must be a valid 10-digit number.')
        return
      }
      if (!secondFirstname.trim() || !secondLastname.trim() || !secondGender || !secondEmail.trim()) {
        setError('Please complete second parent / guardian information.')
        return
      }
    }

    const payload: FullRegisterPayload = {
      firstname,
      lastname,
      gender,
      cellphone,
      email,
      confirm_email: confirmEmail,
      address_street: addressStreet,
      apt,
      city,
      state,
      zip: zip.trim(),
      is_parent: isParent,
      no_second_parent_info: noSecondParentInfo,
      accept_school_policy: acceptPolicy,
      captcha: captchaAnswer,
      second_firstname: secondFirstname,
      second_lastname: secondLastname,
      second_gender: secondGender,
      second_email: secondEmail,
      second_cellphone: secondCellphone,
    }

    setBusy(true)
    try {
      const result = await submitFullRegistration(payload)
      if (!result.ok) {
        setError(result.message)
        if ('errors' in result && result.errors) setFieldErrors(result.errors)
        void loadCaptcha()
        return
      }
      navigate('/login', {
        replace: true,
        state: {
          registered: true,
          message:
            'Registration submitted. Please check your email to activate your account when instructed.',
        },
      })
    } finally {
      setBusy(false)
    }
  }

  const showSecondSection = isParent
  const showSecondFields = isParent && !noSecondParentInfo

  return (
    <div className="ci-auth-bg flex-grow-1 py-4">
      <div className="registration-form ci-parity container mt-3 mb-5">
        <form id="registrationForm" onSubmit={onSubmit}>
          <div className="text-center mb-4">
            <Link to="/">
              <img
                src="/alrahma_logo.png"
                alt="Al Rahma Sunday School"
                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-3"
            style={{ fontFamily: 'Arial, sans-serif' }}
          >
            Registration Form
          </h3>

          <div className="alert alert-info" role="alert">
            - This account is for parents/guardians to manage students. If you already registered
            in a prior year, please reuse your existing account.
            <br />- If you cannot access your old email, reset your password.
          </div>

          <p className="text-center text-secondary mt-3 mb-2 small">
            (All fields with * are required)
          </p>

          {error ? (
            <div className="alert alert-danger" role="alert">
              {error}
            </div>
          ) : null}

          <div className="mb-3">
            <input
              type="text"
              className={`form-control item ${fieldErr('firstname') ? 'is-invalid' : ''}`}
              placeholder="First Name*"
              maxLength={50}
              required
              value={firstname}
              onChange={(e) => setFirstname(e.target.value)}
            />
            {fieldErr('firstname') ? (
              <div className="text-danger small">{fieldErr('firstname')}</div>
            ) : null}
          </div>

          <div className="mb-3">
            <input
              type="text"
              className={`form-control item ${fieldErr('lastname') ? 'is-invalid' : ''}`}
              placeholder="Last Name*"
              maxLength={50}
              required
              value={lastname}
              onChange={(e) => setLastname(e.target.value)}
            />
            {fieldErr('lastname') ? (
              <div className="text-danger small">{fieldErr('lastname')}</div>
            ) : null}
          </div>

          <div className="mb-3">
            <select
              className={`form-select item ${fieldErr('gender') ? 'is-invalid' : ''}`}
              required
              value={gender}
              onChange={(e) => setGender(e.target.value)}
            >
              <option value="" disabled>
                Select Gender*
              </option>
              <option value="Male">Male</option>
              <option value="Female">Female</option>
            </select>
            {fieldErr('gender') ? (
              <div className="text-danger small">{fieldErr('gender')}</div>
            ) : null}
          </div>

          <div className="mb-3">
            <input
              type="tel"
              className={`form-control item ${fieldErr('cellphone') ? 'is-invalid' : ''}`}
              placeholder="Phone - Cell*"
              maxLength={12}
              required
              title="10-digit US phone"
              value={cellphone}
              onChange={(e) => setCellphone(formatUsPhone(e.target.value))}
            />
            {fieldErr('cellphone') ? (
              <div className="text-danger small">{fieldErr('cellphone')}</div>
            ) : null}
          </div>

          <div className="mb-3">
            <input
              type="email"
              className={`form-control item ${fieldErr('email') ? 'is-invalid' : ''}`}
              placeholder="Email*"
              maxLength={50}
              required
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
            {fieldErr('email') ? (
              <div className="text-danger small">{fieldErr('email')}</div>
            ) : null}
          </div>

          <div className="mb-3">
            <input
              type="email"
              className={`form-control item ${fieldErr('confirm_email') ? 'is-invalid' : ''}`}
              placeholder="Confirm Email*"
              maxLength={50}
              required
              value={confirmEmail}
              onChange={(e) => setConfirmEmail(e.target.value)}
              autoComplete="off"
            />
            {fieldErr('confirm_email') ? (
              <div className="text-danger small">{fieldErr('confirm_email')}</div>
            ) : null}
          </div>

          <div className="mb-3">
            <input
              type="text"
              className={`form-control item ${fieldErr('address_street') ? 'is-invalid' : ''}`}
              placeholder="Address - Street*"
              maxLength={50}
              required
              value={addressStreet}
              onChange={(e) => setAddressStreet(e.target.value)}
            />
            {fieldErr('address_street') ? (
              <div className="text-danger small">{fieldErr('address_street')}</div>
            ) : null}
          </div>

          <div className="mb-3">
            <input
              type="text"
              className="form-control item"
              placeholder="Apt"
              maxLength={15}
              value={apt}
              onChange={(e) => setApt(e.target.value)}
            />
          </div>

          <div className="mb-3">
            <input
              type="text"
              className={`form-control item ${fieldErr('city') ? 'is-invalid' : ''}`}
              placeholder="City*"
              maxLength={30}
              required
              value={city}
              onChange={(e) => setCity(e.target.value)}
            />
            {fieldErr('city') ? (
              <div className="text-danger small">{fieldErr('city')}</div>
            ) : null}
          </div>

          <div className="mb-3">
            <select
              className={`form-select item ${fieldErr('state') ? 'is-invalid' : ''}`}
              required
              value={state}
              onChange={(e) => setState(e.target.value)}
            >
              <option value="" disabled>
                Select State*
              </option>
              {NE_STATES.map((s) => (
                <option key={s.abbr} value={s.abbr}>
                  {s.name}
                </option>
              ))}
            </select>
            {fieldErr('state') ? (
              <div className="text-danger small">{fieldErr('state')}</div>
            ) : null}
          </div>

          <div className="mb-3">
            <input
              type="text"
              className={`form-control item ${fieldErr('zip') ? 'is-invalid' : ''}`}
              placeholder="Zip*"
              maxLength={5}
              inputMode="numeric"
              pattern="\d{5}"
              required
              value={zip}
              onChange={(e) => setZip(e.target.value.replace(/\D/g, '').slice(0, 5))}
            />
            {fieldErr('zip') ? (
              <div className="text-danger small">{fieldErr('zip')}</div>
            ) : null}
          </div>

          <div className="form-check mb-3">
            <input
              className="form-check-input"
              type="checkbox"
              id="is_parent"
              checked={isParent}
              onChange={(e) => {
                setIsParent(e.target.checked)
                if (!e.target.checked) {
                  setNoSecondParentInfo(false)
                }
              }}
            />
            <label className="form-check-label" htmlFor="is_parent">
              Check this box if you are a Parent/Guardian
            </label>
          </div>

          {showSecondSection ? (
            <div
              className="mb-4 p-3 rounded"
              style={{ border: '1px solid #ccc' }}
            >
              <h6 className="mb-3">Second Parent/Guardian Information</h6>

              <div className="form-check form-switch mb-3">
                <input
                  className="form-check-input"
                  type="checkbox"
                  id="no_second_parent_info"
                  checked={noSecondParentInfo}
                  onChange={(e) => setNoSecondParentInfo(e.target.checked)}
                />
                <label className="form-check-label" htmlFor="no_second_parent_info">
                  Check this box if no second parent info is available
                </label>
              </div>

              {showSecondFields ? (
                <>
                  <div className="mb-3">
                    <input
                      type="text"
                      className="form-control item"
                      placeholder="First Name*"
                      maxLength={50}
                      value={secondFirstname}
                      onChange={(e) => setSecondFirstname(e.target.value)}
                    />
                    {fieldErr('second_firstname') ? (
                      <div className="text-danger small">{fieldErr('second_firstname')}</div>
                    ) : null}
                  </div>
                  <div className="mb-3">
                    <input
                      type="text"
                      className="form-control item"
                      placeholder="Last Name*"
                      maxLength={50}
                      value={secondLastname}
                      onChange={(e) => setSecondLastname(e.target.value)}
                    />
                    {fieldErr('second_lastname') ? (
                      <div className="text-danger small">{fieldErr('second_lastname')}</div>
                    ) : null}
                  </div>
                  <div className="mb-3">
                    <select
                      className="form-select item"
                      required
                      value={secondGender}
                      onChange={(e) => setSecondGender(e.target.value)}
                    >
                      <option value="" disabled>
                        Select Gender*
                      </option>
                      <option value="Male">Male</option>
                      <option value="Female">Female</option>
                    </select>
                  </div>
                  <div className="mb-3">
                    <input
                      type="email"
                      className="form-control item"
                      placeholder="Email*"
                      maxLength={50}
                      value={secondEmail}
                      onChange={(e) => setSecondEmail(e.target.value)}
                    />
                    {fieldErr('second_email') ? (
                      <div className="text-danger small">{fieldErr('second_email')}</div>
                    ) : null}
                  </div>
                  <div className="mb-3">
                    <input
                      type="tel"
                      className="form-control item"
                      placeholder="Phone - Cell*"
                      maxLength={12}
                      value={secondCellphone}
                      onChange={(e) => setSecondCellphone(formatUsPhone(e.target.value))}
                    />
                    {fieldErr('second_cellphone') ? (
                      <div className="text-danger small">{fieldErr('second_cellphone')}</div>
                    ) : null}
                  </div>
                </>
              ) : null}
            </div>
          ) : null}

          <div className="form-check mb-3">
            <input
              className="form-check-input"
              type="checkbox"
              id="accept_school_policy"
              checked={acceptPolicy}
              required
              onChange={(e) => setAcceptPolicy(e.target.checked)}
            />
            <label className="form-check-label" htmlFor="accept_school_policy">
              I have read and I accept all school policies{' '}
              <button
                type="button"
                className="btn btn-link p-0 small text-success align-baseline"
                onClick={() => void openPolicyModal()}
              >
                (Read school policies here)
              </button>
            </label>
          </div>

          <div className="mb-3">
            <div className="text-center border p-2 bg-light item">
              {captchaLoading ? (
                <span className="text-muted">Loading CAPTCHA…</span>
              ) : (
                <span className="user-select-all">{captchaChallenge}</span>
              )}
            </div>
            <button
              type="button"
              className="btn btn-link btn-sm px-0"
              onClick={() => void loadCaptcha()}
            >
              Refresh CAPTCHA
            </button>
          </div>

          <div className="mb-3">
            <input
              type="text"
              className={`form-control item ${fieldErr('captcha') ? 'is-invalid' : ''}`}
              placeholder="Enter the text above*"
              maxLength={10}
              autoComplete="off"
              required
              value={captchaAnswer}
              onChange={(e) => setCaptchaAnswer(e.target.value)}
            />
            {fieldErr('captcha') ? (
              <div className="text-danger small">{fieldErr('captcha')}</div>
            ) : null}
          </div>

          <div className="mb-3 d-grid gap-2">
            <button type="submit" className="btn btn-success item" disabled={busy || captchaLoading}>
              {busy ? 'Submitting…' : 'Create Account'}
            </button>
            <Link to="/" className="btn btn-secondary item text-center">
              Back to Home
            </Link>
          </div>
        </form>
      </div>

      <div
        className="modal fade"
        id="policyModal"
        tabIndex={-1}
        aria-labelledby="policyModalLabel"
        aria-hidden="true"
      >
        <div className="modal-dialog modal-lg modal-dialog-scrollable">
          <div className="modal-content">
            <div className="modal-header">
              <h5 className="modal-title text-success" id="policyModalLabel">
                School Policies
              </h5>
              <button
                type="button"
                className="btn-close"
                data-bs-dismiss="modal"
                aria-label="Close"
              />
            </div>
            <div className="modal-body">
              {policyLoading ? (
                <p className="text-muted">Loading…</p>
              ) : (
                <div
                  className="policy-html"
                  dangerouslySetInnerHTML={{
                    __html: policyHtml ?? '<p>Click “Read school policies” to load.</p>',
                  }}
                />
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
