import { useEffect, useMemo, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { fetchRegisteredNewStudents } from '../../api/session'
import type { RegisteredNewStudentRow } from '../../api/types'
import { AcademicFilterBar } from '../discounts/AcademicFilterBar'
import {
  EnrollmentStatusBadge,
  NewStudentBadge,
} from './enrollmentStatusUi'

/** Admin new-students list — `GET /api/v1/administrator/enroll-withdrawal/registered-new-students` (JWT). SPA: `/app/admin/enrollment/new-students`. */

function formatRegistrationDate(raw?: string | null): string {
  if (raw == null || String(raw).trim() === '') return '-'
  const s = String(raw)
  const iso = /^(\d{4})-(\d{2})-(\d{2})/.exec(s)
  if (iso) return `${iso[2]}-${iso[3]}-${iso[1]}`
  const d = new Date(s)
  return Number.isNaN(d.getTime()) ? s : `${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}-${d.getFullYear()}`
}

export function RegisteredStudentsPage() {
  type RegisteredStudentsSortKey =
    | 'firstname'
    | 'lastname'
    | 'new_student'
    | 'class_section'
    | 'enrollment_status'
    | 'age'
    | 'registration_date'
  const [searchParams] = useSearchParams()
  const schoolYear = searchParams.get('school_year') ?? undefined
  const semester = searchParams.get('semester') ?? undefined

  const [rows, setRows] = useState<RegisteredNewStudentRow[]>([])
  const [schoolYears, setSchoolYears] = useState<string[] | undefined>(undefined)
  const [totalNew, setTotalNew] = useState<number | undefined>(undefined)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [contactModal, setContactModal] = useState<RegisteredNewStudentRow | null>(null)
  const [tableSearch, setTableSearch] = useState('')
  const [sortConfig, setSortConfig] = useState<{
    key: RegisteredStudentsSortKey
    direction: 'asc' | 'desc'
  }>({
    key: 'lastname',
    direction: 'asc',
  })

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

  function requestSort(key: RegisteredStudentsSortKey) {
    setSortConfig((prev) =>
      prev.key === key
        ? { key, direction: prev.direction === 'asc' ? 'desc' : 'asc' }
        : { key, direction: 'asc' },
    )
  }

  function sortArrow(key: RegisteredStudentsSortKey) {
    if (sortConfig.key !== key) return '↕'
    return sortConfig.direction === 'asc' ? '↑' : '↓'
  }

  const displayedRows = useMemo(() => {
    const query = tableSearch.trim().toLowerCase()
    const filtered = rows.filter((student) => {
      if (!query) return true
      const haystack = [
        student.firstname,
        student.lastname,
        student.new_student,
        student.class_section,
        student.enrollment_status,
        student.age,
        student.registration_date,
        student.parent_firstname,
        student.parent_lastname,
      ]
        .map((value) => String(value ?? '').toLowerCase())
        .join(' ')
      return haystack.includes(query)
    })

    return [...filtered].sort((left, right) => {
      const direction = sortConfig.direction === 'asc' ? 1 : -1
      if (sortConfig.key === 'age') {
        const a = Number(left.age ?? 0)
        const b = Number(right.age ?? 0)
        return (a - b) * direction
      }
      const a = String(left[sortConfig.key] ?? '')
      const b = String(right[sortConfig.key] ?? '')
      return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }) * direction
    })
  }, [rows, tableSearch, sortConfig])

  return (
    <div className="container-fluid">
      <div className="wrapper">
        <div className="content" />
        <h2 className="text-center mt-4 mb-3">
          Registered Students
          {totalNew !== undefined ? (
            <span className="badge bg-secondary ms-2">{totalNew}</span>
          ) : null}
        </h2>
        <AcademicFilterBar schoolYears={schoolYears} />

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

        <div className="d-flex justify-content-end mt-3">
          <div className="input-group" style={{ maxWidth: 360 }}>
            <input
              className="form-control"
              value={tableSearch}
              onChange={(event) => setTableSearch(event.target.value)}
              placeholder="Search students"
            />
            <button className="btn btn-outline-secondary" type="button" onClick={() => setTableSearch('')}>
              Clear
            </button>
          </div>
        </div>

        <div className="table-responsive">
          <table className="table table-bordered table-striped mt-4 align-middle w-100">
            <thead>
              <tr>
                <th role="button" style={{ cursor: 'pointer' }} onClick={() => requestSort('firstname')}>First Name {sortArrow('firstname')}</th>
                <th role="button" style={{ cursor: 'pointer' }} onClick={() => requestSort('lastname')}>Last Name {sortArrow('lastname')}</th>
                <th role="button" style={{ cursor: 'pointer' }} onClick={() => requestSort('new_student')}>New Student {sortArrow('new_student')}</th>
                <th role="button" style={{ cursor: 'pointer' }} onClick={() => requestSort('class_section')}>Current Class {sortArrow('class_section')}</th>
                <th role="button" style={{ cursor: 'pointer' }} onClick={() => requestSort('enrollment_status')}>Actual Status {sortArrow('enrollment_status')}</th>
                <th role="button" style={{ cursor: 'pointer' }} onClick={() => requestSort('age')}>Age {sortArrow('age')}</th>
                <th role="button" style={{ cursor: 'pointer' }} onClick={() => requestSort('registration_date')}>Registration Date {sortArrow('registration_date')}</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>
              {!loading && !error && displayedRows.length === 0 ? (
                <tr>
                  <td colSpan={8} className="text-center">
                    No students found.
                  </td>
                </tr>
              ) : null}
              {displayedRows.map((student) => {
                const sid = Number(student.id ?? 0)
                const familyHref =
                  sid > 0 ? `/app/administrator/family?student_id=${encodeURIComponent(String(sid))}` : '#'
                return (
                  <tr key={sid || `${student.firstname}-${student.lastname}`}>
                    <td>
                      <Link to={familyHref} className="text-decoration-none">
                        {student.firstname ?? ''}
                      </Link>
                    </td>
                    <td>
                      <Link to={familyHref} className="text-decoration-none">
                        {student.lastname ?? ''}
                      </Link>
                    </td>
                    <td>
                      <NewStudentBadge value={student.new_student} />
                    </td>
                    <td>{student.class_section ?? 'Class not Assigned'}</td>
                    <td>
                      <EnrollmentStatusBadge
                        status={student.enrollment_status ?? 'not enrolled'}
                        deniedVariant="light"
                      />
                    </td>
                    <td>{student.age !== undefined && student.age !== null ? String(student.age) : '-'}</td>
                    <td>{formatRegistrationDate(student.registration_date)}</td>
                    <td>
                      <button
                        type="button"
                        className="btn btn-warning btn-sm"
                        onClick={() => setContactModal(student)}
                      >
                        Contact Information
                      </button>
                    </td>
                  </tr>
                )
              })}
            </tbody>
          </table>
        </div>
      </div>

      {contactModal ? (
        <div
          className="modal fade show d-block"
          tabIndex={-1}
          role="dialog"
          aria-modal="true"
          style={{ backgroundColor: 'rgba(0, 0, 0, 0.35)' }}
          onClick={() => setContactModal(null)}
          onKeyDown={(e) => {
            if (e.key === 'Escape') setContactModal(null)
          }}
        >
          <div className="modal-dialog modal-lg modal-dialog-scrollable" onClick={(e) => e.stopPropagation()}>
            <div className="modal-content shadow">
              <div className="modal-header bg-primary text-white">
                <h5 className="modal-title">
                  Contact Info — {contactModal.firstname ?? ''} {contactModal.lastname ?? ''}
                </h5>
                <button
                  type="button"
                  className="btn-close btn-close-white"
                  aria-label="Close"
                  onClick={() => setContactModal(null)}
                />
              </div>
              <div className="modal-body">
                <h5 className="mb-3 border-bottom pb-1">Parent Information</h5>
                <div className="row mb-3">
                  <div className="col-md-6">
                    <p>
                      <strong>Name:</strong>{' '}
                      {`${String(contactModal.parent_firstname ?? '')} ${String(contactModal.parent_lastname ?? '')}`.trim()}
                    </p>
                    <p>
                      <strong>Phone:</strong> {contactModal.parent_phone ?? 'N/A'}
                    </p>
                  </div>
                  <div className="col-md-6">
                    <p>
                      <strong>Email:</strong> {contactModal.parent_email ?? 'N/A'}
                    </p>
                  </div>
                </div>
                <h5 className="mb-3 border-bottom pb-1">Emergency Contact</h5>
                <div className="row">
                  <div className="col-md-6">
                    <p>
                      <strong>Name:</strong> {contactModal.emergency_name ?? 'N/A'}
                    </p>
                    <p>
                      <strong>Relationship:</strong> {contactModal.emergency_relationship ?? 'N/A'}
                    </p>
                    <p>
                      <strong>Phone:</strong> {contactModal.emergency_phone ?? 'N/A'}
                    </p>
                  </div>
                </div>
              </div>
              <div className="modal-footer">
                <button type="button" className="btn btn-secondary" onClick={() => setContactModal(null)}>
                  Close
                </button>
              </div>
            </div>
          </div>
        </div>
      ) : null}
    </div>
  )
}
