import { type FormEvent, useMemo, useState } from 'react'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { sendFamilyComposeEmail } from '../../api/session'

function escapeHtml(s: string): string {
  return s
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
}

/** Plain text → simple HTML (parity with CI rich body when TinyMCE is not loaded). */
function plainTextToHtml(text: string): string {
  const esc = escapeHtml(text)
  const parts = esc.split('\n')
  return `<div>${parts.map((line) => (line === '' ? '<br />' : `<p>${line}</p>`)).join('')}</div>`
}

export function FamilyComposeEmailPage() {
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()
  const name = searchParams.get('name') ?? ''
  const returnUrlParam = searchParams.get('return_url') ?? ''
  const [toField, setToField] = useState(() => searchParams.get('to') ?? '')

  const safeReturn = useMemo(() => {
    if (returnUrlParam.startsWith('/app/')) return returnUrlParam
    return '/app/administrator/family'
  }, [returnUrlParam])

  const [subject, setSubject] = useState('')
  const [body, setBody] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setSubmitting(true)
    setError(null)
    const html = plainTextToHtml(body)
    try {
      await sendFamilyComposeEmail({
        to: toField.trim(),
        subject: subject.trim(),
        html,
        return_url: safeReturn,
      })
      navigate(safeReturn)
    } catch (err: unknown) {
      setError(err instanceof ApiHttpError ? err.message : 'Send failed.')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="container my-4">
      <div className="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
        <div>
          <h2 className="h4 mb-1">Compose Email</h2>
          {name ? <div className="text-muted">{name}</div> : null}
        </div>
        <Link to={safeReturn} className="btn btn-outline-secondary btn-sm">
          Back
        </Link>
      </div>

      <form className="card shadow-sm" onSubmit={onSubmit}>
        <div className="card-body">
          <div className="mb-3">
            <label className="form-label" htmlFor="composeTo">
              To
            </label>
            <input
              type="email"
              className="form-control"
              id="composeTo"
              name="to"
              value={toField}
              onChange={(e) => setToField(e.target.value)}
              required
              placeholder="parent@example.com"
            />
          </div>
          <div className="mb-3">
            <label className="form-label" htmlFor="composeSubject">
              Subject
            </label>
            <input
              type="text"
              className="form-control"
              id="composeSubject"
              name="subject"
              placeholder="Subject"
              required
              value={subject}
              onChange={(e) => setSubject(e.target.value)}
            />
          </div>
          <div className="mb-3">
            <label className="form-label" htmlFor="composeEditor">
              Body
            </label>
            <textarea
              className="form-control"
              id="composeEditor"
              rows={14}
              value={body}
              onChange={(e) => setBody(e.target.value)}
              placeholder="Write your message…"
            />
            <div className="form-text">
              Message is sent as HTML (line breaks preserved). For rich formatting, paste HTML or extend
              this screen with an editor later.
            </div>
          </div>
          <div className="d-flex justify-content-end gap-2">
            <button type="submit" className="btn btn-primary" disabled={submitting || !toField.trim()}>
              {submitting ? 'Sending…' : 'Send Email'}
            </button>
          </div>
          {error ? <div className="alert alert-danger mt-3 mb-0">{error}</div> : null}
        </div>
      </form>
    </div>
  )
}
