import { useCallback, useEffect, useMemo, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { ApiHttpError, apiFetch } from '../../api/http'
import { useAuth } from '../../auth/AuthProvider'
import { TeacherShell } from './TeacherShell'
import { useTeacherResource } from './useTeacherResource'

export type TeacherAttendanceFormStudentRow = {
  student?: Record<string, unknown>
  sunday_statuses?: Record<string, string | null | undefined>
  today?: string | null
  today_reason?: string | null
  locked?: boolean
  locked_source?: string | null
  recent_three?: Array<{ date?: string; status?: string }>
}

export type TeacherAttendanceFormTeacherRow = {
  teacher_id?: number
  position?: string
  name?: string
  sunday_statuses?: Record<string, string | null | undefined>
  today?: string | null
  today_reason?: string | null
}

export type TeacherAttendanceFormPayload = {
  teacher_name?: string | null
  students?: TeacherAttendanceFormStudentRow[]
  teachers?: TeacherAttendanceFormTeacherRow[]
  class_section_id?: number | null
  sunday_dates?: string[]
  current_sunday?: string | null
  enable_attendance?: number | null
  can_edit?: boolean
  class_id?: number | null
  no_school_days?: Record<string, { title?: string; description?: string }>
  today?: string | null
  locked_by_student?: Record<
    string,
    { locked?: boolean; source?: string; reason?: string; status?: string | null }
  >
}

type PlaValue = '' | 'present' | 'late' | 'absent'

function formatShortDate(iso: string): string {
  const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(iso)
  if (m) return `${m[2]}/${m[3]}/${m[1]}`
  return iso
}

/** Calendar day for comparisons (`Y-m-d`), tolerating ISO datetimes from the API. */
function normalizeDateKey(s: string | null | undefined): string {
  if (s == null) return ''
  const t = String(s).trim()
  const m = /^(\d{4}-\d{2}-\d{2})/.exec(t)
  return m ? m[1] : t.slice(0, 10)
}

function isSameCalendarDate(a: string | null | undefined, b: string | null | undefined): boolean {
  if (a == null || b == null || a === '' || b === '') return false
  return normalizeDateKey(a) === normalizeDateKey(b)
}

function statusForDate(
  map: Record<string, string | null | undefined> | undefined,
  columnDate: string,
): string | null | undefined {
  if (!map) return undefined
  const want = normalizeDateKey(columnDate)
  for (const [k, v] of Object.entries(map)) {
    if (normalizeDateKey(k) === want) return v
  }
  return undefined
}

function pickNoSchool(
  map: Record<string, { title?: string; description?: string }> | undefined,
  columnDate: string,
): { title?: string; description?: string } | undefined {
  if (!map) return undefined
  const want = normalizeDateKey(columnDate)
  for (const k of Object.keys(map)) {
    if (normalizeDateKey(k) === want) return map[k]
  }
  return undefined
}

/** Matches backend intent: entry allowed unless explicitly disabled. */
function attendanceEntryEnabled(payload: TeacherAttendanceFormPayload): boolean {
  if (payload.can_edit === false) return false
  return Number(payload.enable_attendance) === 1
}

function unwrapTeacherAttendanceForm(raw: unknown): TeacherAttendanceFormPayload | null {
  if (raw == null || typeof raw !== 'object') return null
  const o = raw as Record<string, unknown>
  const inner = o.data
  if (inner != null && typeof inner === 'object' && !Array.isArray(inner)) {
    return inner as TeacherAttendanceFormPayload
  }
  return raw as TeacherAttendanceFormPayload
}

function studentDisplayName(student: Record<string, unknown> | undefined): string {
  if (!student) return '—'
  const fn = String(student.firstname ?? '').trim()
  const ln = String(student.lastname ?? '').trim()
  const combined = `${fn} ${ln}`.trim()
  return combined || `Student #${String(student.id ?? '')}`
}

/** Laravel / JSON may nest under `student`, `attributes`, or flatten the row. */
function resolveStudentRecord(row: TeacherAttendanceFormStudentRow): Record<string, unknown> | undefined {
  const nested = row.student
  if (nested && typeof nested === 'object' && !Array.isArray(nested)) {
    const n = nested as Record<string, unknown>
    if (n.id != null) return n
    const attrs = n.attributes
    if (attrs && typeof attrs === 'object' && !Array.isArray(attrs)) {
      const a = attrs as Record<string, unknown>
      if (a.id != null) return a
    }
  }
  const flat = row as unknown as Record<string, unknown>
  if (
    flat.id != null &&
    (flat.firstname != null || flat.lastname != null || flat.school_id != null)
  ) {
    return flat
  }
  return undefined
}

/** API usually sends an object keyed by date; tolerate a [{ date, status }] list. */
function keyedSundayStatuses(raw: unknown): Record<string, string | null | undefined> {
  if (raw != null && typeof raw === 'object' && !Array.isArray(raw)) {
    return raw as Record<string, string | null | undefined>
  }
  if (Array.isArray(raw)) {
    const out: Record<string, string | null | undefined> = {}
    for (const item of raw) {
      if (!item || typeof item !== 'object') continue
      const o = item as Record<string, unknown>
      const dk = o.date != null ? normalizeDateKey(String(o.date)) : ''
      if (!dk) continue
      out[dk] = o.status != null ? String(o.status) : undefined
    }
    return out
  }
  return {}
}

/** Map API / legacy values to canonical status for `<select>` and submit. */
function normalizePlaStatus(raw: string | null | undefined): PlaValue {
  if (raw == null || raw === '') return ''
  const s = String(raw).toLowerCase().trim()
  if (s === 'n/a') return ''
  if (s === 'present' || s === 'p') return 'present'
  if (s === 'absent' || s === 'a') return 'absent'
  if (s === 'late' || s === 'l' || s === 'tardy' || s === 't') return 'late'
  return ''
}

function isConcretePla(v: PlaValue | undefined): v is 'present' | 'late' | 'absent' {
  return v === 'present' || v === 'late' || v === 'absent'
}

/** Prefer an explicit P/L/A from local state; otherwise API grid / `today` (fixes `'' ?? fromApi` staying empty). */
function effectiveStudentPla(
  row: TeacherAttendanceFormStudentRow,
  id: number,
  currentSunday: string,
  studentPla: Record<number, PlaValue>,
): PlaValue {
  const fromApi = normalizePlaStatus(
    statusForDate(keyedSundayStatuses(row.sunday_statuses), currentSunday) ?? row.today,
  )
  if (row.locked) return fromApi
  const ui = studentPla[id]
  return isConcretePla(ui) ? ui : fromApi
}

function effectiveTeacherPla(
  t: TeacherAttendanceFormTeacherRow,
  tid: number,
  currentSunday: string,
  teacherPla: Record<number, PlaValue>,
): PlaValue {
  const fromApi = normalizePlaStatus(
    statusForDate(keyedSundayStatuses(t.sunday_statuses), currentSunday) ?? t.today,
  )
  const ui = teacherPla[tid]
  return isConcretePla(ui) ? ui : fromApi
}

function plaBadgeClass(v: PlaValue): string {
  if (v === 'present') return 'text-bg-success'
  if (v === 'late') return 'text-bg-warning text-dark'
  if (v === 'absent') return 'text-bg-danger'
  return 'text-bg-secondary'
}

function plaLetter(v: PlaValue): string {
  if (v === 'present') return 'P'
  if (v === 'late') return 'L'
  if (v === 'absent') return 'A'
  return ''
}

function statusBadgeClass(status: string | null | undefined): string {
  const v = normalizePlaStatus(status)
  if (v) return plaBadgeClass(v)
  const s = String(status ?? '').toLowerCase()
  if (s === 'n/a') return 'text-bg-light text-dark border'
  if (s.includes('excused')) return 'text-bg-info'
  return 'text-bg-secondary'
}

function StatusCell({
  status,
  noSchool,
}: {
  status: string | null | undefined
  noSchool?: { title?: string; description?: string }
}) {
  if (noSchool) {
    const tip = [noSchool.title, noSchool.description].filter(Boolean).join(' — ')
    return (
      <span className="badge text-bg-secondary" title={tip || undefined}>
        No school
      </span>
    )
  }
  if (status == null || status === '') {
    return <span className="text-muted">—</span>
  }
  const v = normalizePlaStatus(status)
  if (v) {
    return (
      <span className={`badge ${plaBadgeClass(v)}`} title={v}>
        {plaLetter(v)}
      </span>
    )
  }
  return <span className={`badge ${statusBadgeClass(status)}`}>{String(status)}</span>
}

const PLA_OPTIONS: Array<{ value: PlaValue; label: string }> = [
  { value: '', label: '—' },
  { value: 'present', label: 'P' },
  { value: 'late', label: 'L' },
  { value: 'absent', label: 'A' },
]

function AttendancePlaSelect({
  value,
  onChange,
  disabled,
  ariaLabel,
}: {
  value: PlaValue
  onChange: (v: PlaValue) => void
  disabled?: boolean
  ariaLabel: string
}) {
  const tone =
    value === 'present'
      ? 'border-success bg-success bg-opacity-10'
      : value === 'late'
        ? 'border-warning bg-warning bg-opacity-25'
        : value === 'absent'
          ? 'border-danger bg-danger bg-opacity-10'
          : 'border-secondary bg-light'

  return (
    <div className={`rounded border ${tone}`} style={{ minWidth: '3.25rem' }}>
      <select
        className="form-select form-select-sm border-0 bg-transparent text-center fw-semibold py-1"
        value={value}
        disabled={disabled}
        onChange={(e) => onChange(e.target.value as PlaValue)}
        aria-label={ariaLabel}
      >
        {PLA_OPTIONS.map((o) => (
          <option key={o.value || 'empty'} value={o.value}>
            {o.label}
          </option>
        ))}
      </select>
    </div>
  )
}

function RecentThreeCell({ rows }: { rows: TeacherAttendanceFormStudentRow['recent_three'] }) {
  if (!rows || rows.length === 0) return <span className="text-muted">—</span>
  return (
    <ul className="list-unstyled small mb-0">
      {rows.map((r, i) => (
        <li key={`${r.date ?? i}-${r.status ?? ''}`}>
          {r.date ? formatShortDate(r.date) : '—'}: {r.status ?? '—'}
        </li>
      ))}
    </ul>
  )
}

function canEditColumn(
  payload: TeacherAttendanceFormPayload,
  columnDate: string,
  resolvedCurrentSunday: string,
  opts?: { noSchool?: boolean; studentLocked?: boolean },
): boolean {
  if (!attendanceEntryEnabled(payload)) return false
  if (!resolvedCurrentSunday || !isSameCalendarDate(columnDate, resolvedCurrentSunday)) return false
  if (opts?.noSchool) return false
  if (opts?.studentLocked) return false
  return true
}

/** Reason text field follows the same Today rules as P/L/A (not locked / no school / entry enabled). */
function reasonFieldEnabled(
  payload: TeacherAttendanceFormPayload,
  currentSunday: string,
  noSchoolDays: Record<string, { title?: string; description?: string }>,
  studentLocked?: boolean,
): boolean {
  if (!attendanceEntryEnabled(payload)) return false
  if (!currentSunday || pickNoSchool(noSchoolDays, currentSunday)) return false
  if (studentLocked) return false
  return true
}

function AttendanceReasonInput({
  value,
  onChange,
  disabled,
  id,
  label,
}: {
  value: string
  onChange: (next: string) => void
  disabled: boolean
  id: string
  label: string
}) {
  return (
    <input
      id={id}
      type="text"
      className="form-control form-control-sm"
      value={value}
      onChange={(e) => onChange(e.target.value)}
      disabled={disabled}
      placeholder={disabled ? undefined : 'Optional'}
      maxLength={255}
      aria-label={label}
    />
  )
}

function AttendanceTables({
  payload,
  noSchoolDays,
  reload,
}: {
  payload: TeacherAttendanceFormPayload
  noSchoolDays: Record<string, { title?: string; description?: string }>
  reload: () => void
}) {
  const dates = payload.sunday_dates ?? []
  const currentSunday =
    payload.current_sunday != null && String(payload.current_sunday).trim() !== ''
      ? String(payload.current_sunday)
      : dates.length >= 3
        ? String(dates[2])
        : dates.length > 0
          ? String(dates[dates.length - 1])
          : ''

  const students = payload.students ?? []
  const teachers = payload.teachers ?? []

  const historicalDates = useMemo(
    () => dates.filter((d) => !isSameCalendarDate(d, currentSunday)),
    [dates, currentSunday],
  )

  const [studentPla, setStudentPla] = useState<Record<number, PlaValue>>({})
  const [teacherPla, setTeacherPla] = useState<Record<number, PlaValue>>({})
  const [studentReason, setStudentReason] = useState<Record<number, string>>({})
  const [teacherReason, setTeacherReason] = useState<Record<number, string>>({})
  const [submitting, setSubmitting] = useState(false)
  const [submitError, setSubmitError] = useState<string | null>(null)
  const [saveFlash, setSaveFlash] = useState<string | null>(null)

  useEffect(() => {
    if (!payload || !currentSunday) return
    const stu = payload.students ?? []
    const tea = payload.teachers ?? []
    const nextS: Record<number, PlaValue> = {}
    for (const row of stu) {
      const rec = resolveStudentRecord(row)
      const id = Number(rec?.id ?? 0)
      if (!id) continue
      nextS[id] = normalizePlaStatus(
        statusForDate(keyedSundayStatuses(row.sunday_statuses), currentSunday) ?? row.today,
      )
    }
    setStudentPla(nextS)

    const nextSr: Record<number, string> = {}
    for (const row of stu) {
      const rec = resolveStudentRecord(row)
      const id = Number(rec?.id ?? 0)
      if (!id) continue
      nextSr[id] = row.today_reason != null ? String(row.today_reason) : ''
    }
    setStudentReason(nextSr)

    const nextT: Record<number, PlaValue> = {}
    const nextTr: Record<number, string> = {}
    for (const t of tea) {
      const tid = Number(t.teacher_id ?? 0)
      if (!tid) continue
      nextT[tid] = normalizePlaStatus(
        statusForDate(keyedSundayStatuses(t.sunday_statuses), currentSunday) ?? t.today,
      )
      nextTr[tid] = t.today_reason != null ? String(t.today_reason) : ''
    }
    setTeacherPla(nextT)
    setTeacherReason(nextTr)
  }, [payload, currentSunday])

  const allFilledForSubmit = useMemo(() => {
    for (const row of students) {
      const id = Number(resolveStudentRecord(row)?.id ?? 0)
      if (!id) continue
      if (row.locked) continue
      if (effectiveStudentPla(row, id, currentSunday, studentPla) === '') return false
    }
    for (const t of teachers) {
      const tid = Number(t.teacher_id ?? 0)
      if (!tid) continue
      if (effectiveTeacherPla(t, tid, currentSunday, teacherPla) === '') return false
    }
    return students.length > 0 && teachers.length > 0
  }, [students, teachers, studentPla, teacherPla, currentSunday])

  const submitDateKey = normalizeDateKey(currentSunday)
  const canSubmitForm =
    attendanceEntryEnabled(payload) &&
    !!submitDateKey &&
    !pickNoSchool(noSchoolDays, currentSunday) &&
    allFilledForSubmit

  const handleSave = useCallback(async () => {
    setSubmitError(null)
    setSaveFlash(null)
    if (!canSubmitForm || !submitDateKey) return

    const sectionId = payload.class_section_id
    if (sectionId == null || Number(sectionId) <= 0) {
      setSubmitError('Missing class section.')
      return
    }

    const attendance = students
      .map((row) => {
        const id = Number(resolveStudentRecord(row)?.id ?? 0)
        if (!id) return null
        const chosen = effectiveStudentPla(row, id, currentSunday, studentPla)
        if (!chosen) return null
        const schoolId = resolveStudentRecord(row)?.school_id
        const reasonText = row.locked
          ? row.today_reason != null
            ? String(row.today_reason)
            : undefined
          : studentReason[id]?.trim() || undefined

        return {
          student_id: id,
          school_id: schoolId != null && schoolId !== '' ? String(schoolId) : undefined,
          status: chosen,
          reason: reasonText,
          is_reported: 'no',
        }
      })
      .filter(Boolean) as Array<{
      student_id: number
      school_id?: string
      status: 'present' | 'late' | 'absent'
      reason?: string
      is_reported: string
    }>

    if (attendance.length === 0) {
      setSubmitError('No student rows to save.')
      return
    }

    const teachersPayload: Record<string, { status: string; reason?: string | null }> = {}
    for (const t of teachers) {
      const tid = Number(t.teacher_id ?? 0)
      if (!tid) continue
      const st = effectiveTeacherPla(t, tid, currentSunday, teacherPla)
      if (!st) {
        setSubmitError('Please set attendance (P / L / A) for all staff.')
        return
      }
      const tr = teacherReason[tid]?.trim()
      teachersPayload[String(tid)] = {
        status: st,
        ...(tr ? { reason: tr } : {}),
      }
    }

    if (Object.keys(teachersPayload).length === 0) {
      setSubmitError('No staff rows to save.')
      return
    }

    setSubmitting(true)
    try {
      await apiFetch<{ ok?: boolean; message?: string }>('/api/v1/attendance/teacher/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          class_section_id: sectionId,
          class_id: payload.class_id ?? undefined,
          date: submitDateKey,
          attendance,
          teachers: teachersPayload,
        }),
      })
      setSaveFlash('Attendance submitted successfully.')
      reload()
    } catch (e: unknown) {
      setSubmitError(e instanceof ApiHttpError ? e.message : 'Unable to save attendance.')
    } finally {
      setSubmitting(false)
    }
  }, [
    canSubmitForm,
    payload,
    reload,
    studentPla,
    studentReason,
    submitDateKey,
    currentSunday,
    teacherPla,
    teacherReason,
    students,
    teachers,
  ])

  return (
    <div className="d-flex flex-column gap-4">
      {saveFlash ? (
        <div className="alert alert-success py-2 mb-0" role="status">
          {saveFlash}
        </div>
      ) : null}
      {submitError ? (
        <div className="alert alert-danger py-2 mb-0" role="alert">
          {submitError}
        </div>
      ) : null}

      <section>
        <h2 className="h5 mb-2">Staff attendance</h2>
        {teachers.length === 0 ? (
          <p className="text-muted mb-0">No staff rows returned for this section.</p>
        ) : (
          <div className="table-responsive">
            <table className="table table-bordered table-sm align-middle">
              <thead className="table-light">
                <tr>
                  <th>Name</th>
                  <th>Role</th>
                  {historicalDates.map((d) => (
                    <th key={`th-staff-${d}`} className="text-center text-nowrap">
                      {formatShortDate(d)}
                      {pickNoSchool(noSchoolDays, d) ? (
                        <div className="fw-normal small text-muted">No school</div>
                      ) : null}
                    </th>
                  ))}
                  <th className="text-center text-nowrap">
                    Today
                    {currentSunday ? (
                      <div className="fw-normal small text-muted">{formatShortDate(currentSunday)}</div>
                    ) : null}
                    {pickNoSchool(noSchoolDays, currentSunday) ? (
                      <div className="fw-normal small text-muted">No school</div>
                    ) : null}
                  </th>
                  <th>Reason</th>
                </tr>
              </thead>
              <tbody>
                {teachers.map((t) => {
                  const tid = Number(t.teacher_id ?? 0)
                  return (
                    <tr key={t.teacher_id ?? t.name}>
                      <td>{t.name ?? '—'}</td>
                      <td className="text-capitalize">{t.position === 'ta' ? 'TA' : t.position ?? '—'}</td>
                      {historicalDates.map((d) => (
                        <td key={`${t.teacher_id}-${d}`} className="text-center">
                          <StatusCell
                            status={statusForDate(keyedSundayStatuses(t.sunday_statuses), d)}
                            noSchool={pickNoSchool(noSchoolDays, d)}
                          />
                        </td>
                      ))}
                      <td className="text-center">
                        {canEditColumn(payload, currentSunday, currentSunday, {
                          noSchool: !!pickNoSchool(noSchoolDays, currentSunday),
                        }) ? (
                          <div className="d-inline-flex justify-content-center">
                            <AttendancePlaSelect
                              value={teacherPla[tid] ?? ''}
                              onChange={(v) => setTeacherPla((prev) => ({ ...prev, [tid]: v }))}
                              ariaLabel={`Attendance for ${t.name ?? 'staff'} on Today`}
                            />
                          </div>
                        ) : (
                          <StatusCell
                            status={statusForDate(keyedSundayStatuses(t.sunday_statuses), currentSunday)}
                            noSchool={pickNoSchool(noSchoolDays, currentSunday)}
                          />
                        )}
                      </td>
                      <td style={{ minWidth: '10rem' }}>
                        <AttendanceReasonInput
                          id={`staff-reason-${tid}`}
                          label={`Reason for ${t.name ?? 'staff'}`}
                          value={teacherReason[tid] ?? ''}
                          onChange={(next) => setTeacherReason((prev) => ({ ...prev, [tid]: next }))}
                          disabled={
                            !reasonFieldEnabled(payload, currentSunday, noSchoolDays, false)
                          }
                        />
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        )}
      </section>

      <section>
        <h2 className="h5 mb-2">Student attendance</h2>
        {students.length === 0 ? (
          <p className="text-muted mb-0">No students in this class for the current term.</p>
        ) : (
          <div className="table-responsive">
            <table className="table table-bordered table-sm align-middle">
              <thead className="table-light">
                <tr>
                  <th>School ID</th>
                  <th>Name</th>
                  {historicalDates.map((d) => (
                    <th key={`th-stu-${d}`} className="text-center text-nowrap">
                      {formatShortDate(d)}
                      {pickNoSchool(noSchoolDays, d) ? (
                        <div className="fw-normal small text-muted">No school</div>
                      ) : null}
                    </th>
                  ))}
                  <th className="text-center text-nowrap">
                    Today
                    {currentSunday ? (
                      <div className="fw-normal small text-muted">{formatShortDate(currentSunday)}</div>
                    ) : null}
                    {pickNoSchool(noSchoolDays, currentSunday) ? (
                      <div className="fw-normal small text-muted">No school</div>
                    ) : null}
                  </th>
                  <th>Reason</th>
                  <th>Recent (last 3)</th>
                </tr>
              </thead>
              <tbody>
                {students.map((row, idx) => {
                  const st = resolveStudentRecord(row)
                  const sid = st?.id != null ? String(st.id) : `row-${idx}`
                  const id = Number(st?.id ?? 0)
                  const schoolId = st?.school_id != null ? String(st.school_id) : '—'
                  return (
                    <tr key={sid}>
                      <td>{schoolId}</td>
                      <td>{studentDisplayName(st)}</td>
                      {historicalDates.map((d) => (
                        <td key={`${sid}-${d}`} className="text-center">
                          <StatusCell
                            status={statusForDate(keyedSundayStatuses(row.sunday_statuses), d)}
                            noSchool={pickNoSchool(noSchoolDays, d)}
                          />
                        </td>
                      ))}
                      <td className="text-center">
                        {canEditColumn(payload, currentSunday, currentSunday, {
                          noSchool: !!pickNoSchool(noSchoolDays, currentSunday),
                          studentLocked: !!row.locked,
                        }) ? (
                          <div className="d-inline-flex justify-content-center">
                            <AttendancePlaSelect
                              value={studentPla[id] ?? ''}
                              onChange={(v) => setStudentPla((prev) => ({ ...prev, [id]: v }))}
                              ariaLabel={`Attendance for ${studentDisplayName(st)} on Today`}
                            />
                          </div>
                        ) : (
                          <StatusCell
                            status={statusForDate(keyedSundayStatuses(row.sunday_statuses), currentSunday)}
                            noSchool={pickNoSchool(noSchoolDays, currentSunday)}
                          />
                        )}
                      </td>
                      <td style={{ minWidth: '10rem' }}>
                        <AttendanceReasonInput
                          id={`stu-reason-${id}`}
                          label={`Reason for ${studentDisplayName(st)}`}
                          value={studentReason[id] ?? ''}
                          onChange={(next) => setStudentReason((prev) => ({ ...prev, [id]: next }))}
                          disabled={
                            !reasonFieldEnabled(payload, currentSunday, noSchoolDays, !!row.locked)
                          }
                        />
                      </td>
                      <td className="small">
                        <RecentThreeCell rows={row.recent_three} />
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        )}
      </section>

      <div className="d-flex flex-wrap align-items-center gap-2 pt-1 border-top">
        {attendanceEntryEnabled(payload) &&
        currentSunday &&
        !pickNoSchool(noSchoolDays, currentSunday) ? (
          <button
            type="button"
            className="btn btn-primary btn-sm"
            disabled={!canSubmitForm || submitting}
            onClick={() => void handleSave()}
          >
            {submitting ? 'Saving…' : 'Submit attendance (Today)'}
          </button>
        ) : null}
        {!allFilledForSubmit &&
        attendanceEntryEnabled(payload) &&
        currentSunday &&
        !pickNoSchool(noSchoolDays, currentSunday) ? (
          <span className="small text-muted">Choose P, L, or A for every student and staff member for Today.</span>
        ) : null}
      </div>
    </div>
  )
}

/** `teacher/showupdate_attendance.php` — grid + P/L/A for current Sunday; POST `/api/v1/attendance/teacher/submit`. */
export function TeacherShowupdateAttendancePage() {
  const { user } = useAuth()
  const [search] = useSearchParams()
  const sectionId = search.get('class_section_id')?.trim() || (user?.class_section_id != null ? String(user.class_section_id) : '')
  const path = useMemo(() => {
    const q = sectionId ? `?class_section_id=${encodeURIComponent(sectionId)}` : ''
    return `/showupdate-attendance${q}`
  }, [sectionId])

  const { data: raw, loading, error, reload } = useTeacherResource<unknown>(path)
  const payload = useMemo(() => unwrapTeacherAttendanceForm(raw), [raw])
  const noSchoolDays = payload?.no_school_days ?? {}

  const subtitleParts: string[] = []
  if (payload?.teacher_name) subtitleParts.push(`Logged in as ${payload.teacher_name}`)
  if (payload?.class_section_id != null && payload.class_section_id > 0) {
    subtitleParts.push(`Section ID ${payload.class_section_id}`)
  }
  if (payload?.current_sunday) {
    subtitleParts.push(`Today ${formatShortDate(payload.current_sunday)}`)
  }

  return (
    <TeacherShell
      title="Attendance"
      subtitle={subtitleParts.length ? subtitleParts.join(' · ') : undefined}
      loading={loading}
      error={error}
    >
      <div className="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
        <div className="small text-muted">
          {Number(payload?.enable_attendance) === 1 ? (
            <span>Attendance entry is enabled for the school.</span>
          ) : (
            <span>Attendance entry is disabled in configuration.</span>
          )}
          {payload?.can_edit === false ? (
            <span className="ms-1">You do not have edit access from this summary.</span>
          ) : null}
        </div>
        <button type="button" className="btn btn-outline-secondary btn-sm" onClick={() => reload()}>
          Refresh
        </button>
      </div>

      {!loading && raw != null && payload == null ? (
        <div className="alert alert-warning">
          Unexpected response shape. Raw payload (for debugging):
          <pre className="small mb-0 mt-2 bg-light p-2 rounded overflow-auto" style={{ maxHeight: 240 }}>
            {JSON.stringify(raw, null, 2)}
          </pre>
        </div>
      ) : null}

      {payload ? <AttendanceTables payload={payload} noSchoolDays={noSchoolDays} reload={reload} /> : null}
    </TeacherShell>
  )
}
