import { useEffect, useState } from 'react'
import { Link, useParams, useSearchParams } from 'react-router-dom'
import { fetchAttendanceStudentViolationsView } from '../../api/session'
import { ATTENDANCE_VIOLATIONS_PENDING_PATH } from './attendancePaths'

/** Port of `Views/attendance/view.php` — student violation history. */
export function AttendanceStudentViolationsViewPage() {
  const { studentId } = useParams()
  const [searchParams] = useSearchParams()
  const code = searchParams.get('code')
  const incidentDate = searchParams.get('incident_date')
  const includeNotified = searchParams.get('include_notified')

  const [data, setData] = useState<Record<string, unknown> | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!studentId) return
    let cancelled = false
    ;(async () => {
      setLoading(true)
      try {
        const res = await fetchAttendanceStudentViolationsView(studentId, {
          code,
          incident_date: incidentDate,
          include_notified: includeNotified ?? undefined,
        })
        if (!cancelled) setData(res)
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : 'Unable to load.')
      } finally {
        if (!cancelled) setLoading(false)
      }
    })()
    return () => {
      cancelled = true
    }
  }, [studentId, code, incidentDate, includeNotified])

  const title = typeof data?.title === 'string' ? data.title : 'Attendance History'
  const attendance = (data?.attendance as Array<Record<string, unknown>> | undefined) ?? []
  const showViolationSummary = Boolean(data?.show_violation_summary)
  const viCode = data?.violation_code
  const viDateRaw = String(data?.violation_date ?? '')
  const viNotif = data?.violation_notified

  return (
    <div className="container-xxl py-4">
      <h2 className="text-center mt-2 mb-3">{title}</h2>

      <div className="card mb-4">
        <div className="card-body">
          <Link to={ATTENDANCE_VIOLATIONS_PENDING_PATH} className="btn btn-secondary mb-3">
            Back to Attendance
          </Link>

          <p className="text-muted small mb-3">
            Showing absences and lates for this student within the violation window.
          </p>

          <h5 className="card-title mb-3">Attendance Violations</h5>

          {loading ? (
            <p className="text-muted">Loading…</p>
          ) : error ? (
            <div className="alert alert-danger">{error}</div>
          ) : (
            <div className="table-responsive">
              <table className="table table-striped attendance-history-table">
                <thead>
                  <tr>
                    <th>Date</th>
                    <th>Status</th>
                    <th>Reason</th>
                    <th>Notified</th>
                    <th>Reported</th>
                  </tr>
                </thead>
                <tbody>
                  {showViolationSummary && (viCode || viDateRaw) ? (
                    <tr className="table-info">
                      <td>{viDateRaw ? formatMdY(viDateRaw.slice(0, 10)) : '—'}</td>
                      <td>{String(viCode ?? '—')}</td>
                      <td>Violation summary</td>
                      <td>{truthy(viNotif) ? 'Yes' : 'No'}</td>
                      <td>—</td>
                    </tr>
                  ) : null}
                  {attendance.length === 0 ? (
                    <tr>
                      <td colSpan={5} className="text-center text-muted">
                        No attendance violations found for this student.
                      </td>
                    </tr>
                  ) : (
                    attendance.map((record, i) => (
                      <ViolationRow key={i} record={record} />
                    ))
                  )}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

function truthy(v: unknown): boolean {
  if (v === true || v === 1) return true
  if (typeof v === 'string') return ['yes', '1', 'true'].includes(v.toLowerCase().trim())
  return false
}

function ViolationRow({ record }: { record: Record<string, unknown> }) {
  const dateStr = String(record.date ?? '').slice(0, 10)
  const dateLabel = dateStr ? formatMdY(dateStr) : '—'
  const statusRaw = String(record.status ?? '').toLowerCase().trim()
  const reason = String(record.reason ?? '').trim()
  const isNotified = truthy(record.is_notified)
  const isReported = truthy(record.is_reported)

  const isAbs =
    statusRaw === 'absent' ||
    statusRaw === 'abs' ||
    statusRaw === 'a' ||
    statusRaw.startsWith('abs')
  const isLate = statusRaw === 'late' || statusRaw === 'l' || statusRaw.startsWith('late')

  let status = statusRaw !== '' ? capitalize(statusRaw) : 'Unknown'
  if (isAbs) status = isReported ? 'Reported Absence' : 'Unreported Absence'
  else if (isLate) status = isReported ? 'Reported Late' : 'Unreported Late'

  return (
    <tr>
      <td>{dateLabel}</td>
      <td>{status}</td>
      <td>{reason !== '' ? reason : 'No reason provided'}</td>
      <td>{isNotified ? 'Yes' : 'No'}</td>
      <td>{isReported ? 'Yes' : 'No'}</td>
    </tr>
  )
}

function capitalize(s: string): string {
  return s ? s.charAt(0).toUpperCase() + s.slice(1) : s
}

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}`
}
