import { useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { fetchIncidentAnalysis, type IncidentAnalysisStudent } from '../../api/flags'
import { AcademicFilterBar } from '../discounts/AcademicFilterBar'
import {
  descriptionForLog,
  formatIncidentDatetime,
  incidentTypeLabel,
} from './flagRowUtils'

/** CI `flags/incident_analysis.php` — per-student rollup + expandable logs. */
export function IncidentAnalysisPage() {
  const [searchParams] = useSearchParams()
  const [students, setStudents] = useState<IncidentAnalysisStudent[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    let cancelled = false
    setLoading(true)
    fetchIncidentAnalysis(searchParams)
      .then((data) => {
        if (!cancelled) {
          setStudents(data)
          setError(null)
        }
      })
      .catch((e: unknown) => {
        if (!cancelled)
          setError(e instanceof ApiHttpError ? e.message : 'Unable to load incident analysis.')
      })
      .finally(() => {
        if (!cancelled) setLoading(false)
      })
    return () => {
      cancelled = true
    }
  }, [searchParams])

  return (
    <div className="container-fluid">
      <h2 className="text-center mt-4 mb-3">Incident Analysis</h2>
      <div className="d-flex gap-2 justify-content-end mb-3 flex-wrap">
        <Link className="btn btn-secondary" to="/app/administrator/flags/management">
          Back to Pending Incidents
        </Link>
        <Link className="btn btn-secondary" to="/app/administrator/flags/processed">
          View Processed Incidents
        </Link>
      </div>

      <AcademicFilterBar />

      {error ? <div className="alert alert-danger">{error}</div> : null}
      {loading ? <p className="text-muted">Loading…</p> : null}

      <div className="table-responsive">
        <table className="table table-bordered">
          <thead>
            <tr>
              <th>Student Name</th>
              <th>Grade</th>
              <th>Total Incidents</th>
              <th>Open</th>
              <th>Closed</th>
              <th>Canceled</th>
              <th>Last Incident</th>
              <th>Log &amp; Follow-up</th>
            </tr>
          </thead>
          <tbody>
            {!loading && students.length === 0 ? (
              <tr>
                <td colSpan={8}>No incidents found.</td>
              </tr>
            ) : null}
            {students.map((student, si) => (
              <tr key={`${student.student_name}-${student.grade}-${si}`}>
                <td>{student.student_name ?? ''}</td>
                <td>{student.grade ?? ''}</td>
                <td>{student.total ?? 0}</td>
                <td>{student.open ?? 0}</td>
                <td>{student.closed ?? 0}</td>
                <td>{student.canceled ?? 0}</td>
                <td>{formatIncidentDatetime(student.last_incident)}</td>
                <td>
                  <details>
                    <summary>View log</summary>
                    <div className="table-responsive mt-2">
                      <table className="table table-sm table-bordered mb-0">
                        <thead>
                          <tr>
                            <th>Datetime</th>
                            <th>Incident Type</th>
                            <th>State</th>
                            <th>Description</th>
                            <th>Action Taken</th>
                          </tr>
                        </thead>
                        <tbody>
                          {!student.logs?.length ? (
                            <tr>
                              <td colSpan={5}>No incident logs found.</td>
                            </tr>
                          ) : null}
                          {student.logs?.map((log, li) => (
                            <tr key={li}>
                              <td>{formatIncidentDatetime(log.flag_datetime)}</td>
                              <td>{incidentTypeLabel(log.flag)}</td>
                              <td>{log.flag_state ?? ''}</td>
                              <td>{descriptionForLog(log)}</td>
                              <td>{log.action_taken ?? 'N/A'}</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </details>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}
