import { useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { fetchFlagsProcessed, type IncidentFlagRow } from '../../api/flags'
import { AcademicFilterBar } from '../discounts/AcademicFilterBar'
import {
  descriptionForFlag,
  formatIncidentDatetime,
  incidentTypeLabel,
  lastUpdaterCell,
} from './flagRowUtils'

/** CI `flags/processed_flags.php` — processed / closed / canceled incidents. */
export function ProcessedFlagsPage() {
  const [searchParams] = useSearchParams()
  const [rows, setRows] = useState<IncidentFlagRow[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

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

  return (
    <div className="container-fluid">
      <h2 className="text-center mt-4 mb-3">Processed Incidents</h2>
      <div className="d-flex justify-content-end mb-3">
        <Link className="btn btn-secondary" to="/app/administrator/flags/management">
          Back to Pending 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>Last Updater</th>
              <th>Student Name</th>
              <th>Grade</th>
              <th>Incident Type</th>
              <th>Description</th>
              <th>Datetime</th>
              <th>Incident State</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {!loading && rows.length === 0 ? (
              <tr>
                <td colSpan={8}>No processed incidents found.</td>
              </tr>
            ) : null}
            {rows.map((flag, i) => (
              <tr key={flag.id ?? i}>
                <td>{lastUpdaterCell(flag)}</td>
                <td>{flag.student_name ?? ''}</td>
                <td>{flag.grade ?? ''}</td>
                <td>{incidentTypeLabel(flag.flag)}</td>
                <td>{descriptionForFlag(flag)}</td>
                <td>{formatIncidentDatetime(flag.flag_datetime)}</td>
                <td>{flag.flag_state ?? ''}</td>
                <td>{flag.action_taken ?? 'N/A'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}
