import { useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { fetchRefundsList, type RefundListRow } from '../../api/refunds'
import { AcademicFilterBar } from '../discounts/AcademicFilterBar'

function fmtMoney(n: unknown): string {
  const v = Number(n)
  return Number.isFinite(v) ? v.toFixed(2) : '—'
}

function pickStr(row: Record<string, unknown>, keys: string[]): string {
  for (const k of keys) {
    const v = row[k]
    if (v != null && String(v).trim() !== '') return String(v)
  }
  return '—'
}

/** CI `refunds/list.php` — `GET /api/v1/administrator/refunds/list` (JWT). SPA `/app/refunds/list`. */

export function RefundsListPage() {
  const [searchParams] = useSearchParams()
  const schoolYear = searchParams.get('school_year') ?? ''
  const semester = searchParams.get('semester') ?? ''

  const [rows, setRows] = useState<RefundListRow[]>([])
  const [schoolYears, setSchoolYears] = useState<string[] | undefined>(undefined)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    let cancelled = false
    setLoading(true)
    setError(null)
    fetchRefundsList({
      school_year: schoolYear || undefined,
      semester: semester || undefined,
    })
      .then((d) => {
        if (cancelled) return
        setRows(d.refunds ?? [])
        setSchoolYears(d.school_years)
      })
      .catch((e: unknown) => {
        if (!cancelled)
          setError(e instanceof ApiHttpError ? e.message : 'Could not load refunds.')
      })
      .finally(() => {
        if (!cancelled) setLoading(false)
      })
    return () => {
      cancelled = true
    }
  }, [schoolYear, semester])

  return (
    <div className="container-fluid py-3">
      <h2 className="text-center mt-2 mb-3">Refunds</h2>

      <AcademicFilterBar schoolYears={schoolYears} />

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

      <div className="table-responsive">
        <table className="table table-bordered table-striped align-middle">
          <thead className="table-light">
            <tr>
              <th>ID</th>
              <th>Date</th>
              <th>Parent</th>
              <th>Student</th>
              <th>Invoice</th>
              <th className="text-end">Amount</th>
              <th>Status</th>
              <th>Notes</th>
            </tr>
          </thead>
          <tbody>
            {!loading && !error && rows.length === 0 ? (
              <tr>
                <td colSpan={8} className="text-center text-muted py-4">
                  No refunds for this filter.
                </td>
              </tr>
            ) : null}
            {rows.map((r, i) => {
              const row = r as Record<string, unknown>
              const id = pickStr(row, ['id'])
              const pid = Number(row.parent_id ?? row.guardian_id ?? 0)
              const parentName = pickStr(row, ['parent_name', 'guardian_name', 'parent'])
              const studentName = pickStr(row, ['student_name', 'student', 'student_full_name'])
              const invoice = pickStr(row, ['invoice_number', 'invoice_no', 'invoice_id'])
              const amt = row.amount ?? row.refund_amount ?? row.total_refund ?? row.total
              const dt = pickStr(row, ['refund_date', 'date', 'created_at', 'processed_at'])
              const status = pickStr(row, ['status', 'state'])
              const notes = pickStr(row, ['notes', 'description', 'reason', 'memo'])
              const key = id !== '—' ? id : `row-${i}`
              return (
                <tr key={key}>
                  <td>{id}</td>
                  <td>{dt}</td>
                  <td>
                    {pid > 0 ? (
                      <Link
                        className="text-decoration-none"
                        to={`/app/administrator/family?guardian_id=${encodeURIComponent(String(pid))}`}
                      >
                        {parentName}
                      </Link>
                    ) : (
                      parentName
                    )}
                  </td>
                  <td>{studentName}</td>
                  <td>{invoice}</td>
                  <td className="text-end">${fmtMoney(amt)}</td>
                  <td>{status}</td>
                  <td className="small">{notes}</td>
                </tr>
              )
            })}
          </tbody>
        </table>
      </div>
    </div>
  )
}
