import { type FormEvent, useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { fetchAttendanceTrackingStudents, recordAttendanceTrackingEntry } from '../../api/session'

/** Port of `Views/attendance/attendance_tracking.php` — record + student summary list. */
export function AttendanceTrackingPage() {
  const [title, setTitle] = useState('Attendance Tracking')
  const [students, setStudents] = useState<Array<Record<string, unknown>>>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [studentId, setStudentId] = useState('')
  const [recDate, setRecDate] = useState(() => new Date().toISOString().slice(0, 10))
  const [isPresent, setIsPresent] = useState('1')
  const [reason, setReason] = useState('')
  const [isReported, setIsReported] = useState(false)
  const [notified, setNotified] = useState(false)
  const [flash, setFlash] = useState<string | null>(null)

  useEffect(() => {
    let cancelled = false
    ;(async () => {
      setLoading(true)
      try {
        const data = await fetchAttendanceTrackingStudents()
        if (!cancelled) {
          setTitle(typeof data.title === 'string' ? data.title : 'Attendance Tracking')
          setStudents(Array.isArray(data.students) ? data.students : [])
          setError(null)
        }
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : 'Unable to load.')
      } finally {
        if (!cancelled) setLoading(false)
      }
    })()
    return () => {
      cancelled = true
    }
  }, [])

  async function onRecord(e: FormEvent) {
    e.preventDefault()
    setFlash(null)
    try {
      await recordAttendanceTrackingEntry({
        student_id: Number(studentId),
        date: recDate,
        is_present: isPresent === '1',
        reason: isPresent === '0' ? reason : '',
        is_reported: isReported ? 1 : 0,
        notified: notified ? 1 : 0,
      })
      setFlash('Recorded.')
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Record failed.')
    }
  }

  const showReason = isPresent === '0'

  return (
    <div className="container-xxl py-4">
      <h2 className="text-center mt-2 mb-3">{title}</h2>
      {flash ? <div className="alert alert-success">{flash}</div> : null}
      {error ? <div className="alert alert-danger">{error}</div> : null}

      <div className="card mb-4">
        <div className="card-header">
          <h5 className="mb-0">Record Attendance</h5>
        </div>
        <div className="card-body">
          <form onSubmit={onRecord}>
            <div className="row">
              <div className="col-md-4 mb-3">
                <label className="form-label" htmlFor="student_id">
                  Student
                </label>
                <select
                  id="student_id"
                  className="form-select"
                  required
                  value={studentId}
                  onChange={(ev) => setStudentId(ev.target.value)}
                >
                  <option value="">Select Student</option>
                  {students.map((s, i) => {
                    const id = String(s.id ?? s.student_id ?? '')
                    const name = String((s.name ?? `${s.firstname ?? ''} ${s.lastname ?? ''}`.trim()) || id)
                    return (
                      <option key={id || String(i)} value={id}>
                        {name}
                      </option>
                    )
                  })}
                </select>
              </div>
              <div className="col-md-3 mb-3">
                <label className="form-label" htmlFor="date">
                  Date
                </label>
                <input
                  id="date"
                  type="date"
                  className="form-control"
                  required
                  value={recDate}
                  onChange={(ev) => setRecDate(ev.target.value)}
                />
              </div>
              <div className="col-md-3 mb-3">
                <label className="form-label" htmlFor="is_present">
                  Status
                </label>
                <select
                  id="is_present"
                  className="form-select"
                  required
                  value={isPresent}
                  onChange={(ev) => setIsPresent(ev.target.value)}
                >
                  <option value="1">Present</option>
                  <option value="0">Absent</option>
                </select>
              </div>
              <div className="col-md-2 mb-3 d-flex align-items-end">
                <button type="submit" className="btn btn-primary">
                  Record
                </button>
              </div>
            </div>

            {showReason ? (
              <div className="row mt-2">
                <div className="col-md-6 mb-3">
                  <label className="form-label" htmlFor="reason">
                    Reason for Absence
                  </label>
                  <textarea
                    id="reason"
                    className="form-control"
                    rows={2}
                    value={reason}
                    onChange={(ev) => setReason(ev.target.value)}
                  />
                </div>
                <div className="col-md-6 mb-3 d-flex align-items-end gap-4 flex-wrap">
                  <div className="form-check">
                    <input
                      className="form-check-input"
                      type="checkbox"
                      id="is_reported"
                      checked={isReported}
                      onChange={(ev) => setIsReported(ev.target.checked)}
                    />
                    <label className="form-check-label" htmlFor="is_reported">
                      Reported Absence
                    </label>
                  </div>
                  <div className="form-check">
                    <input
                      className="form-check-input"
                      type="checkbox"
                      id="notified"
                      checked={notified}
                      onChange={(ev) => setNotified(ev.target.checked)}
                    />
                    <label className="form-check-label" htmlFor="notified">
                      Parent Notified
                    </label>
                  </div>
                </div>
              </div>
            ) : null}
          </form>
        </div>
      </div>

      <div className="card">
        <div className="card-header">
          <h5 className="mb-0">Student List</h5>
        </div>
        <div className="card-body">
          {loading ? (
            <p className="text-muted mb-0">Loading students…</p>
          ) : (
            <div className="table-responsive">
              <table className="table table-striped">
                <thead>
                  <tr>
                    <th>Student Name</th>
                    <th>Total Absences</th>
                    <th>Last Absence Date</th>
                    <th>Last Absence Reason</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {students.map((student, idx) => {
                    const sid = String(student.id ?? student.student_id ?? idx)
                    const name = String(student.name ?? `${student.firstname ?? ''} ${student.lastname ?? ''}`.trim())
                    const totalAbs = student.total_absences
                    const last = student.last_absence as Record<string, unknown> | undefined
                    const lastDate = last?.date ? String(last.date).slice(0, 10) : ''
                    const lastReason = last?.reason != null ? String(last.reason) : ''
                    return (
                      <tr key={sid}>
                        <td>{name}</td>
                        <td>{totalAbs != null ? String(totalAbs) : '—'}</td>
                        <td>{lastDate ? formatMdY(lastDate) : 'N/A'}</td>
                        <td>{lastReason || 'N/A'}</td>
                        <td>
                          <Link className="btn btn-sm btn-info" to={`/app/administrator/attendance/view/${sid}`}>
                            View Details
                          </Link>
                        </td>
                      </tr>
                    )
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

function formatMdY(ymd: string): string {
  if (!/^\d{4}-\d{2}-\d{2}$/.test(ymd)) return ymd
  const [y, m, d] = ymd.split('-')
  return `${m}-${d}-${y}`
}
