import { type FormEvent, useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { fetchAttendanceComposeEmailContext, sendAttendanceViolationEmail } from '../../api/session'
import { ATTENDANCE_VIOLATIONS_PENDING_PATH } from './attendancePaths'

/** Port of `Views/attendance/compose_email.php` — rich body via large textarea (TinyMCE optional later). */
export function ComposeAttendanceEmailPage() {
  const [searchParams] = useSearchParams()
  const studentId = searchParams.get('student_id') ?? ''
  const code = searchParams.get('code') ?? ''
  const variant = searchParams.get('variant') ?? ''
  const incidentDate =
    searchParams.get('incident_date') ?? new Date().toISOString().slice(0, 10)

  const [to, setTo] = useState('')
  const [subject, setSubject] = useState('')
  const [bodyHtml, setBodyHtml] = useState('')
  const [studentName, setStudentName] = useState('')
  const [secondaryEmail, setSecondaryEmail] = useState('')
  const [secondaryName, setSecondaryName] = useState('')
  const [schoolYear, setSchoolYear] = useState('')
  const [semester, setSemester] = useState('')
  const missingParams = !studentId || !code
  const [loading, setLoading] = useState(!missingParams)
  const [error, setError] = useState<string | null>(
    missingParams ? 'Missing student_id or code query parameters.' : null,
  )
  const [msg, setMsg] = useState<string | null>(null)
  const [saving, setSaving] = useState(false)

  useEffect(() => {
    if (missingParams) return
    let cancelled = false
    ;(async () => {
      try {
        const ctx = await fetchAttendanceComposeEmailContext({
          studentId,
          code,
          variant: variant || null,
          incidentDate,
        })
        if (cancelled) return
        setTo(String(ctx.parent_email ?? ctx.to ?? ''))
        setSubject(String(ctx.subject ?? ''))
        const initial = String(ctx.body_html ?? ctx.body_text ?? '')
        setBodyHtml(initial)
        setStudentName(String(ctx.student_name ?? ''))
        setSecondaryEmail(String(ctx.secondary_email ?? ''))
        setSecondaryName(String(ctx.secondary_name ?? ''))
        setSchoolYear(String(ctx.school_year ?? ''))
        setSemester(String(ctx.semester ?? ''))
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : 'Unable to load compose context.')
      } finally {
        if (!cancelled) setLoading(false)
      }
    })()
    return () => {
      cancelled = true
    }
  }, [studentId, code, variant, incidentDate, missingParams])

  async function onSubmit(e: FormEvent) {
    e.preventDefault()
    setSaving(true)
    setError(null)
    setMsg(null)
    try {
      await sendAttendanceViolationEmail({
        student_id: studentId,
        code,
        variant,
        incident_date: incidentDate,
        to,
        subject,
        body_html: bodyHtml,
      })
      setMsg('Email sent.')
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Send failed.')
    } finally {
      setSaving(false)
    }
  }

  if (loading) {
    return (
      <div className="container my-4">
        <p className="text-muted">Loading compose form…</p>
      </div>
    )
  }

  return (
    <div className="container my-4">
      <h2 className="text-center mb-3">Compose Attendance Email</h2>
      {error ? <div className="alert alert-danger">{error}</div> : null}
      {msg ? <div className="alert alert-success">{msg}</div> : null}

      <div className="card shadow-sm">
        <div className="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
          <div>
            <strong>{studentName}</strong>
            <span className="badge bg-secondary ms-2">
              {code}
              {variant ? ` • ${variant}` : ''}
            </span>
          </div>
          <div>
            <span className="badge bg-primary">School Year: {schoolYear}</span>
            {semester ? (
              <span className="badge bg-info text-dark ms-1">Semester: {semester}</span>
            ) : null}
          </div>
        </div>
        <div className="card-body">
          <form onSubmit={onSubmit}>
            <div className="mb-3">
              <label className="form-label">To</label>
              <input
                type="email"
                className="form-control"
                value={to}
                onChange={(ev) => setTo(ev.target.value)}
                required
              />
              <div className="form-text">Primary parent email (you can change it here).</div>
            </div>

            {secondaryEmail ? (
              <div className="alert alert-light border d-flex align-items-start mb-3">
                <div className="me-2">
                  <i className="bi bi-files" aria-hidden />
                </div>
                <div>
                  <strong>Second Parent (CC):</strong> {secondaryEmail}
                  {secondaryName ? ` — ${secondaryName}` : ''}
                </div>
              </div>
            ) : null}

            <div className="mb-3">
              <label className="form-label">Subject</label>
              <input
                type="text"
                className="form-control"
                value={subject}
                onChange={(ev) => setSubject(ev.target.value)}
                required
              />
            </div>

            <div className="mb-3">
              <label className="form-label">Body (HTML allowed)</label>
              <textarea
                className="form-control font-monospace"
                rows={14}
                value={bodyHtml}
                onChange={(ev) => setBodyHtml(ev.target.value)}
              />
              <div className="form-text">Paste HTML or plain text; backend may sanitize.</div>
            </div>

            <div className="d-flex gap-2">
              <Link to={ATTENDANCE_VIOLATIONS_PENDING_PATH} className="btn btn-outline-secondary">
                Cancel
              </Link>
              <button type="submit" className="btn btn-primary" disabled={saving}>
                {saving ? 'Sending…' : 'Send Email'}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  )
}
