/**
 * Barrel: class progress + student score card live under `pages/admin/`.
 * Emergency contact admin screens remain here.
 */
export { ClassProgressListPage as AdminClassProgressListPage } from './classProgress/ClassProgressListPage'
export { ClassProgressViewPage as AdminClassProgressViewPage } from './classProgress/ClassProgressViewPage'
export { AdminStudentScoreCardPage } from './admin/AdminStudentScoreCardPage'

import { type FormEvent, useEffect, useMemo, useState, type ReactNode } from 'react'
import { Link, useNavigate, useParams, useSearchParams } from 'react-router-dom'
import {
  deleteAdministratorEmergencyContact,
  fetchAdministratorEmergencyContact,
  fetchAdministratorEmergencyContacts,
  updateAdministratorEmergencyContact,
} from '../api/session'
import type { EmergencyContactGroupRow } from '../api/types'

function PageShell({ title, children }: { title: string; children: ReactNode }) {
  return (
    <div className="container-fluid py-3">
      <div className="mb-4">
        <h2 className="h4 mb-1">{title}</h2>
      </div>
      {children}
    </div>
  )
}

type FlatContact = {
  contactId: number
  parentId: number
  parentName: string
  students: string
  contactName: string
  relation: string
  phone: string
}

export function AdminEmergencyContactIndexPage() {
  const [groups, setGroups] = useState<EmergencyContactGroupRow[]>([])
  const [error, setError] = useState<string | null>(null)
  const [search, setSearch] = useState('')
  const [sortKey, setSortKey] = useState<keyof Omit<FlatContact, 'contactId' | 'parentId'>>('parentName')
  const [sortDir, setSortDir] = useState<'asc' | 'desc'>('asc')

  async function load() {
    try {
      const data = await fetchAdministratorEmergencyContacts()
      setGroups(data.groups ?? [])
      setError(null)
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Unable to load emergency contacts.')
    }
  }

  useEffect(() => { void load() }, [])

  async function removeContact(contactId: number, parentId: number) {
    await deleteAdministratorEmergencyContact(contactId, parentId)
    await load()
  }

  function toggleSort(key: typeof sortKey) {
    if (sortKey === key) setSortDir((d) => (d === 'asc' ? 'desc' : 'asc'))
    else { setSortKey(key); setSortDir('asc') }
  }

  const flatRows = useMemo<FlatContact[]>(() =>
    groups.flatMap((group) =>
      (group.contacts ?? []).map((contact) => ({
        contactId:   contact.id,
        parentId:    group.parent_id,
        parentName:  group.parent_name ?? '',
        students:    (group.students ?? []).map((s) => `${s.firstname ?? ''} ${s.lastname ?? ''}`.trim()).join(', '),
        contactName: contact.name ?? '',
        relation:    contact.relation ?? '',
        phone:       contact.cellphone || group.parent_phones?.join(' / ') || '',
      }))
    ),
  [groups])

  const displayed = useMemo(() => {
    const q = search.trim().toLowerCase()
    let rows = q
      ? flatRows.filter((r) =>
          r.parentName.toLowerCase().includes(q) ||
          r.students.toLowerCase().includes(q) ||
          r.contactName.toLowerCase().includes(q) ||
          r.relation.toLowerCase().includes(q) ||
          r.phone.includes(q),
        )
      : flatRows
    return [...rows].sort((a, b) => {
      const cmp = a[sortKey].localeCompare(b[sortKey], undefined, { sensitivity: 'base' })
      return sortDir === 'asc' ? cmp : -cmp
    })
  }, [flatRows, search, sortKey, sortDir])

  function SortTh({ col, label }: { col: typeof sortKey; label: string }) {
    const active = sortKey === col
    return (
      <th
        role="button"
        style={{ cursor: 'pointer', userSelect: 'none', whiteSpace: 'nowrap' }}
        onClick={() => toggleSort(col)}
      >
        {label} <span className="text-muted small">{active ? (sortDir === 'asc' ? '▲' : '▼') : '⇅'}</span>
      </th>
    )
  }

  return (
    <PageShell title="Emergency Contact Information">
      {error ? <div className="alert alert-danger">{error}</div> : null}

      <div className="d-flex justify-content-between align-items-center mb-2 flex-wrap gap-2">
        <span className="text-muted small">{displayed.length} record{displayed.length !== 1 ? 's' : ''}</span>
        <input
          id="ec-search"
          name="search"
          type="search"
          className="form-control form-control-sm"
          style={{ maxWidth: 260 }}
          placeholder="Search name, student, relation, phone…"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
      </div>

      <div className="table-responsive">
        <table className="table table-bordered table-striped align-middle">
          <thead className="table-dark">
            <tr>
              <SortTh col="parentName" label="Parent Name" />
              <SortTh col="students" label="Students" />
              <SortTh col="contactName" label="Contact Name" />
              <SortTh col="relation" label="Relation" />
              <SortTh col="phone" label="Phone" />
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {displayed.length === 0 ? (
              <tr>
                <td colSpan={6} className="text-muted">No emergency contacts found.</td>
              </tr>
            ) : (
              displayed.map((row) => (
                <tr key={row.contactId}>
                  <td>{row.parentName || '—'}</td>
                  <td>{row.students || '—'}</td>
                  <td>{row.contactName || '—'}</td>
                  <td>{row.relation || '—'}</td>
                  <td>{row.phone || 'N/A'}</td>
                  <td className="d-flex gap-2">
                    <Link
                      className="btn btn-sm btn-primary"
                      to={`/app/administrator/emergency-contacts/${row.contactId}/edit?parent_id=${row.parentId}`}
                    >
                      Edit
                    </Link>
                    <button
                      className="btn btn-sm btn-danger"
                      type="button"
                      onClick={() => void removeContact(row.contactId, row.parentId)}
                    >
                      Delete
                    </button>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </PageShell>
  )
}

export function AdminEmergencyContactEditPage() {
  const { contactId } = useParams()
  const [searchParams] = useSearchParams()
  const parentId = Number(searchParams.get('parent_id') ?? 0)
  const [form, setForm] = useState({ name: '', cellphone: '', email: '', relation: '' })
  const [error, setError] = useState<string | null>(null)
  const [message, setMessage] = useState<string | null>(null)
  const navigate = useNavigate()

  useEffect(() => {
    if (!contactId || !parentId) return
    ;(async () => {
      try {
        const data = await fetchAdministratorEmergencyContact(Number(contactId), parentId)
        setForm({
          name: data.contact.name ?? '',
          cellphone: data.contact.cellphone ?? '',
          email: data.contact.email ?? '',
          relation: data.contact.relation ?? '',
        })
        setError(null)
      } catch (e) {
        setError(e instanceof Error ? e.message : 'Unable to load emergency contact.')
      }
    })()
  }, [contactId, parentId])

  async function onSubmit(e: FormEvent) {
    e.preventDefault()
    if (!contactId || !parentId) return
    try {
      await updateAdministratorEmergencyContact(Number(contactId), {
        parent_id: parentId,
        name: form.name,
        cellphone: form.cellphone,
        email: form.email || null,
        relation: form.relation || null,
      })
      setMessage('Emergency contact updated.')
      setError(null)
      navigate('/app/administrator/emergency-contacts')
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unable to update emergency contact.')
    }
  }

  return (
    <PageShell title="Edit Emergency Contact">
      {error ? <div className="alert alert-danger">{error}</div> : null}
      {message ? <div className="alert alert-success">{message}</div> : null}
      <div className="card shadow-sm" style={{ maxWidth: 720 }}>
        <div className="card-body">
          <form onSubmit={(e) => void onSubmit(e)}>
            <div className="mb-3">
              <label className="form-label">Name</label>
              <input
                className="form-control"
                value={form.name}
                onChange={(e) => setForm((current) => ({ ...current, name: e.target.value }))}
                required
              />
            </div>
            <div className="mb-3">
              <label className="form-label">Phone</label>
              <input
                className="form-control"
                value={form.cellphone}
                onChange={(e) => setForm((current) => ({ ...current, cellphone: e.target.value }))}
                required
              />
            </div>
            <div className="mb-3">
              <label className="form-label">Email</label>
              <input
                type="email"
                className="form-control"
                value={form.email}
                onChange={(e) => setForm((current) => ({ ...current, email: e.target.value }))}
              />
            </div>
            <div className="mb-3">
              <label className="form-label">Relation</label>
              <input
                className="form-control"
                value={form.relation}
                onChange={(e) => setForm((current) => ({ ...current, relation: e.target.value }))}
              />
            </div>
            <div className="d-flex gap-2">
              <button className="btn btn-primary" type="submit">
                Update
              </button>
              <Link className="btn btn-secondary" to="/app/administrator/emergency-contacts">
                Cancel
              </Link>
            </div>
          </form>
        </div>
      </div>
    </PageShell>
  )
}
