import { useEffect, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { fetchParentAttendance } from '../../api/session'
import type { ParentAttendanceRow } from '../../api/types'

export function ParentAttendancePage() {
  const [params, setParams] = useSearchParams()
  const schoolYearParam = params.get('school_year')

  const [rows, setRows] = useState<ParentAttendanceRow[]>([])
  const [schoolYears, setSchoolYears] = useState<{ school_year: string }[]>([])
  const [selectedYear, setSelectedYear] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let cancelled = false
    ;(async () => {
      setLoading(true)
      try {
        const data = await fetchParentAttendance(schoolYearParam)
        if (cancelled) return
        setRows(data.attendance ?? [])
        setSchoolYears(data.schoolYears ?? [])
        setSelectedYear(data.selectedYear ?? null)
        setError(null)
      } catch (e) {
        if (!cancelled) {
          setRows([])
          setSchoolYears([])
          setSelectedYear(null)
          setError(e instanceof Error ? e.message : 'Unable to load attendance.')
        }
      } finally {
        if (!cancelled) setLoading(false)
      }
    })()
    return () => {
      cancelled = true
    }
  }, [schoolYearParam])

  function onYearChange(next: string) {
    const nextParams = new URLSearchParams(params)
    if (next) nextParams.set('school_year', next)
    else nextParams.delete('school_year')
    setParams(nextParams)
  }

  const yearOptions =
    schoolYears.length > 0
      ? schoolYears
      : selectedYear
        ? [{ school_year: selectedYear }]
        : []

  return (
    <div>
      <div className="text-center mb-4">
        <h2 className="h4 text-success" style={{ fontFamily: 'Arial, sans-serif' }}>
          Attendance Record
        </h2>
      </div>

      <form
        className="row g-2 align-items-end mb-4"
        onSubmit={(e) => {
          e.preventDefault()
        }}
      >
        <div className="col-auto">
          <label className="form-label mb-0" htmlFor="school_year">
            School year
          </label>
          <select
            id="school_year"
            className="form-select"
            value={schoolYearParam ?? selectedYear ?? ''}
            onChange={(e) => onYearChange(e.target.value)}
            disabled={loading || yearOptions.length === 0}
          >
            {yearOptions.length === 0 ? (
              <option value="">—</option>
            ) : (
              yearOptions.map((y) => (
                <option key={y.school_year} value={y.school_year}>
                  {y.school_year}
                </option>
              ))
            )}
          </select>
        </div>
        <div className="col-auto">
          <button type="button" className="btn btn-success" disabled={loading}>
            Filter
          </button>
        </div>
      </form>

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

      {loading ? (
        <p className="text-muted">Loading…</p>
      ) : rows.length === 0 ? (
        <p className="text-muted">No attendance rows for this school year.</p>
      ) : (
        <div className="table-responsive">
          <table className="table table-striped table-bordered">
            <thead>
              <tr>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Date</th>
                <th>Status</th>
                <th>Reason</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((row, i) => (
                <tr key={`${row.date}-${row.firstname}-${row.lastname}-${i}`}>
                  <td>{row.firstname}</td>
                  <td>{row.lastname}</td>
                  <td>{row.date}</td>
                  <td>{row.status}</td>
                  <td>{row.reason ?? '—'}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <p className="small text-muted mt-4 mb-0">
        
        {' · '}
       
      </p>
    </div>
  )
}
