import { type FormEvent, useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { fetchBelowSixtyEmailEditor, postBelowSixtyEmail } from '../../api/grading'
import { GRADING_BELOW_SIXTY_PATH } from './gradingPaths'

/** CI `grading/below_sixty_email_editor.php` — rich email replaced with HTML textarea until an editor is added. */
export function BelowSixtyEmailEditorPage() {
  const [searchParams] = useSearchParams()
  const studentId = searchParams.get('student_id') ?? ''
  const semester = searchParams.get('semester') ?? ''
  const schoolYear = searchParams.get('school_year') ?? ''

  const [html, setHtml] = useState('')
  const [subjectLine, setSubjectLine] = useState('')
  const [studentName, setStudentName] = useState('')
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState<string | null>(null)

  useEffect(() => {
    if (!studentId) {
      setLoading(false)
      return
    }
    let c = false
    setLoading(true)
    fetchBelowSixtyEmailEditor(searchParams)
      .then((p) => {
        if (c) return
        setStudentName(p.studentName ?? '')
        setSubjectLine(p.subject ?? '')
        setHtml(p.html ?? '')
        setError(null)
      })
      .catch((e: unknown) => {
        if (!c) setError(e instanceof ApiHttpError ? e.message : 'Unable to load email editor.')
      })
      .finally(() => {
        if (!c) setLoading(false)
      })
    return () => {
      c = true
    }
  }, [searchParams, studentId])

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setSaving(true)
    setError(null)
    setSuccess(null)
    try {
      await postBelowSixtyEmail({
        student_id: Number(studentId),
        semester,
        school_year: schoolYear,
        subject: subjectLine || undefined,
        html,
      })
      setSuccess('Email sent.')
    } catch (err: unknown) {
      setError(err instanceof ApiHttpError ? err.message : 'Send failed.')
    } finally {
      setSaving(false)
    }
  }

  const backQs = searchParams.toString()

  if (!studentId) {
    return (
      <div className="container mt-4">
        <div className="alert alert-info">
          Missing <code>student_id</code> in the URL.
        </div>
        <Link className="btn btn-secondary" to={`${GRADING_BELOW_SIXTY_PATH}${backQs ? `?${backQs}` : ''}`}>
          Back to Below 60
        </Link>
      </div>
    )
  }

  return (
    <div className="container py-4">
      <div className="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
        <h2 className="mb-0">Email parent — below 60</h2>
        <Link
          className="btn btn-outline-secondary btn-sm"
          to={`${GRADING_BELOW_SIXTY_PATH}${backQs ? `?${backQs}` : ''}`}
        >
          Back
        </Link>
      </div>

      {studentName ? <p className="text-muted mb-2">Student: {studentName}</p> : null}
      {semester || schoolYear ? (
        <p className="small text-muted mb-3">
          {semester} {schoolYear}
        </p>
      ) : null}

      {error ? <div className="alert alert-danger">{error}</div> : null}
      {success ? <div className="alert alert-success">{success}</div> : null}
      {loading ? <p className="text-muted">Loading…</p> : null}

      {!loading ? (
        <form onSubmit={(ev) => void onSubmit(ev)}>
          <div className="mb-3">
            <label className="form-label">Subject</label>
            <input
              type="text"
              className="form-control"
              value={subjectLine}
              onChange={(e) => setSubjectLine(e.target.value)}
            />
          </div>
          <div className="mb-3">
            <label className="form-label">Message (HTML)</label>
            <textarea
              className="form-control font-monospace"
              rows={18}
              value={html}
              onChange={(e) => setHtml(e.target.value)}
            />
          </div>
          <button type="submit" className="btn btn-primary" disabled={saving}>
            {saving ? 'Sending…' : 'Send email'}
          </button>
        </form>
      ) : null}
    </div>
  )
}
