import { Link } from 'react-router-dom'
import { useEffect, useState } from 'react'
import { fetchParentEmergencyContacts } from '../../api/session'
import type { ParentEmergencyContactRow } from '../../api/types'
import { ParentParityShell } from './ParentParityShell'

/** CI `parent/edit-emergency-contact` (no id) — GET /api/v1/parents/emergency-contacts */
export function ParentEmergencyContactsPage() {
  const [rows, setRows] = useState<ParentEmergencyContactRow[]>([])
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let cancelled = false
    ;(async () => {
      setLoading(true)
      try {
        const data = await fetchParentEmergencyContacts()
        if (cancelled) return
        setRows(data.contacts ?? [])
        setError(null)
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : 'Unable to load contacts.')
      } finally {
        if (!cancelled) setLoading(false)
      }
    })()
    return () => {
      cancelled = true
    }
  }, [])

  return (
    <ParentParityShell
      title="Emergency contacts"
      ciViewFile="edit_emergency_contact.php"
      legacyCiRoutes={['/parent/edit-emergency-contact']}
    >
      {error ? <div className="alert alert-warning small">{error}</div> : null}
      {loading ? (
        <p className="text-muted small">Loading…</p>
      ) : rows.length === 0 ? (
        <p className="text-muted small mb-0">No emergency contacts.</p>
      ) : (
        <ul className="list-unstyled mb-0">
          {rows.map((c) => (
            <li key={c.id} className="border-bottom py-2">
              <Link to={`/app/parent/emergency-contact/${c.id}`}>
                <strong>{c.name || 'Contact'}</strong>
              </Link>
              <div className="small text-muted">
                {[c.cellphone, c.email].filter(Boolean).join(' · ') || '—'}
              </div>
            </li>
          ))}
        </ul>
      )}
    </ParentParityShell>
  )
}
