import { type FormEvent, useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import {
  fetchBelowSixtyDecisionEmailEditor,
  postBelowSixtyDecisionEmail,
} from '../../api/grading'
import { GRADING_BELOW_SIXTY_DECISIONS_PATH } from './gradingPaths'

export function BelowSixtyDecisionEmailEditorPage() {
  const [searchParams] = useSearchParams()
  const studentId = searchParams.get('student_id') ?? ''
  const schoolYear = searchParams.get('school_year') ?? ''

  const [html, setHtml] = useState('')
  const [subjectLine, setSubjectLine] = useState('')
  const [studentName, setStudentName] = useState('')
  const [decision, setDecision] = 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 || !schoolYear) {
      setLoading(false)
      return
    }
    let cancelled = false
    setLoading(true)
    fetchBelowSixtyDecisionEmailEditor(searchParams)
      .then((payload) => {
        if (cancelled) return
        setStudentName(payload.student_name ?? '')
        setDecision(payload.decision ?? '')
        setSubjectLine(payload.subject ?? '')
        setHtml(payload.html ?? '')
        setError(null)
      })
      .catch((e: unknown) => {
        if (!cancelled) {
          setError(e instanceof ApiHttpError ? e.message : 'Unable to load the decision email editor.')
        }
      })
      .finally(() => {
        if (!cancelled) setLoading(false)
      })
    return () => {
      cancelled = true
    }
  }, [schoolYear, searchParams, studentId])

  async function onSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    setSaving(true)
    setError(null)
    setSuccess(null)
    try {
      await postBelowSixtyDecisionEmail({
        student_id: Number(studentId),
        school_year: schoolYear,
        subject: subjectLine || undefined,
        html,
      })
      setSuccess('Decision email sent.')
    } catch (e: unknown) {
      setError(e instanceof ApiHttpError ? e.message : 'Unable to send the decision email.')
    } finally {
      setSaving(false)
    }
  }

  const backHref = `${GRADING_BELOW_SIXTY_DECISIONS_PATH}?school_year=${encodeURIComponent(schoolYear)}`

  if (!studentId || !schoolYear) {
    return (
      <div className="container mt-4">
        <div className="alert alert-info">Missing <code>student_id</code> or <code>school_year</code>.</div>
        <Link className="btn btn-secondary" to={backHref}>
          Back to Decisions
        </Link>
      </div>
    )
  }

  return (
    <div className="container py-4">
      <div className="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
        <div>
          <h2 className="mb-1">Send Decision Email</h2>
          <div className="text-muted">
            {studentName || 'Student'} • {schoolYear}
            {decision ? ` — ${decision}` : ''}
          </div>
        </div>
        <Link className="btn btn-outline-secondary btn-sm" to={backHref}>
          Back to Decisions
        </Link>
      </div>

      {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={(event) => void onSubmit(event)} className="card shadow-sm">
          <div className="card-body">
            <div className="mb-3">
              <label className="form-label">Subject</label>
              <input
                type="text"
                className="form-control"
                value={subjectLine}
                onChange={(event) => setSubjectLine(event.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={(event) => setHtml(event.target.value)}
              />
            </div>
            <div className="d-flex justify-content-end gap-2">
              <Link className="btn btn-outline-secondary" to={backHref}>
                Cancel
              </Link>
              <button type="submit" className="btn btn-primary" disabled={saving}>
                {saving ? 'Sending…' : 'Send Email'}
              </button>
            </div>
          </div>
        </form>
      ) : null}
    </div>
  )
}
