import { type FormEvent, useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { useSchoolYearOptions } from '../../hooks/useSchoolYearOptions'
import { fetchParentAttendanceReportsAdmin } from '../../api/session'
import type { ParentAttendanceAdminReportRow } from '../../api/types'

/** Port of `Views/attendance/parent_reports.php` */
export function ParentAttendanceReportsAdminPage() {
  const [searchParams, setSearchParams] = useSearchParams()
  const schoolYear = searchParams.get('school_year') ?? ''
  const semester = searchParams.get('semester') ?? ''
  const start = searchParams.get('start') ?? new Date().toISOString().slice(0, 10)
  const end = searchParams.get('end') ?? ''

  const [rows, setRows] = useState<ParentAttendanceAdminReportRow[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const { options, selectedYear } = useSchoolYearOptions({
    preferredYear: schoolYear,
  })

  useEffect(() => {
    let cancelled = false
    ;(async () => {
      setLoading(true)
      try {
        const data = await fetchParentAttendanceReportsAdmin({
          schoolYear: schoolYear || null,
          semester: semester || null,
          start: start || null,
          end: end || null,
        })
        if (!cancelled) setRows(data.rows ?? [])
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : 'Unable to load reports.')
      } finally {
        if (!cancelled) setLoading(false)
      }
    })()
    return () => {
      cancelled = true
    }
  }, [schoolYear, semester, start, end])

  function apply(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    const fd = new FormData(e.currentTarget)
    const p = new URLSearchParams()
    const sy = String(fd.get('school_year') ?? '')
    const sem = String(fd.get('semester') ?? '')
    const st = String(fd.get('start') ?? '')
    const en = String(fd.get('end') ?? '')
    if (sy) p.set('school_year', sy)
    if (sem) p.set('semester', sem)
    if (st) p.set('start', st)
    if (en) p.set('end', en)
    setSearchParams(p)
  }

  return (
    <div className="container-xxl py-4">
      <div className="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-3">
        <h2 className="mb-0">Parent Attendance Reports</h2>
        <small className="text-muted">Submitted by parents (absent/late/early dismissal)</small>
      </div>

      <form className="row gy-2 gx-3 align-items-end mb-4" onSubmit={apply}>
        <div className="col-md-3">
          <label className="form-label">School Year</label>
          <select name="school_year" className="form-select" defaultValue={schoolYear || selectedYear}>
            {(options.length > 0 ? options : [{ value: selectedYear, label: selectedYear }]).map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
        </div>
        <div className="col-md-2">
          <label className="form-label">Semester</label>
          <select name="semester" className="form-select" defaultValue={semester}>
            <option value="">—</option>
            <option value="Fall">Fall</option>
            <option value="Spring">Spring</option>
          </select>
        </div>
        <div className="col-md-2">
          <label className="form-label">Start Date</label>
          <input type="date" name="start" className="form-control" defaultValue={start} />
        </div>
        <div className="col-md-2">
          <label className="form-label">End Date</label>
          <input type="date" name="end" className="form-control" defaultValue={end} />
        </div>
        <div className="col-md-3 d-flex gap-2">
          <button type="submit" className="btn btn-secondary mt-4">
            Apply
          </button>
          <Link className="btn btn-outline-secondary mt-4" to="/app/administrator/attendance/parent-reports">
            Reset
          </Link>
        </div>
      </form>

      {error ? <div className="alert alert-danger">{error}</div> : null}

      <div className="card shadow-sm">
        <div className="card-body table-responsive">
          {loading ? (
            <p className="text-muted mb-0">Loading…</p>
          ) : (
            <table className="table table-striped align-middle">
              <thead>
                <tr>
                  <th>Date</th>
                  <th>Student</th>
                  <th>Class/Section</th>
                  <th>Type</th>
                  <th>Time</th>
                  <th>Reason</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                {rows.length === 0 ? (
                  <tr>
                    <td colSpan={7} className="text-center text-muted">
                      No reports found for the selected range.
                    </td>
                  </tr>
                ) : (
                  rows.map((r, i) => (
                    <tr key={i}>
                      <td>{formatCellDate(r.report_date)}</td>
                      <td>{`${String(r['firstname'] ?? '')} ${String(r['lastname'] ?? '')}`.trim()}</td>
                      <td>{String(r.class_section_name ?? '—')}</td>
                      <td className="text-capitalize">{String(r.type ?? '').replace(/_/g, ' ')}</td>
                      <td>{timeCell(r)}</td>
                      <td style={{ maxWidth: 360, whiteSpace: 'normal' }}>{String(r.reason ?? '')}</td>
                      <td>
                        <span
                          className={`badge bg-${
                            r.status === 'processed' ? 'success' : r.status === 'seen' ? 'info' : 'secondary'
                          }`}
                        >
                          {String(r.status ?? 'new').replace(/^\w/, (c) => c.toUpperCase())}
                        </span>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </div>
  )
}

function formatCellDate(v: unknown): string {
  if (v == null || v === '') return ''
  const s = String(v).slice(0, 10)
  if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) return String(v)
  const [y, m, d] = s.split('-')
  return `${m}-${d}-${y}`
}

function timeCell(r: ParentAttendanceAdminReportRow): string {
  const t = String(r.type ?? '')
  const arrival = r['arrival_time']
  const dismiss = r['dismiss_time']
  if (t === 'late' && arrival) return `Arrival: ${String(arrival).slice(0, 5)}`
  if (t === 'early_dismissal' && dismiss) return `Dismiss: ${String(dismiss).slice(0, 5)}`
  return '—'
}
