import { useEffect, useMemo, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import {
  fetchSchoolYearParentBalances,
  fetchSchoolYearPromotionPreview,
  fetchSchoolYearSummary,
  type SchoolYearParentBalancePreview,
  type SchoolYearPromotionPreview,
  type SchoolYearSummary,
} from '../../api/schoolYears'
import { SchoolYearStatusBadge } from '../../components/schoolYear'

function normalizeApiError(error: unknown, fallback: string): string {
  if (error instanceof ApiHttpError) return error.message || fallback
  if (error instanceof Error) return error.message
  return fallback
}

function formatMoney(value: number | null | undefined): string {
  return Number(value ?? 0).toLocaleString(undefined, {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })
}

export function SchoolYearDetailPage() {
  const [searchParams] = useSearchParams()
  const schoolYear = searchParams.get('school_year')?.trim() ?? ''
  const [summary, setSummary] = useState<SchoolYearSummary | null>(null)
  const [promotionPreview, setPromotionPreview] = useState<SchoolYearPromotionPreview | null>(null)
  const [parentBalances, setParentBalances] = useState<SchoolYearParentBalancePreview | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!schoolYear) {
      setError('Missing school_year query parameter.')
      setLoading(false)
      return
    }

    let cancelled = false
    setLoading(true)
    setError(null)

    ;(async () => {
      try {
        const [nextSummary, nextPromotion, nextBalances] = await Promise.all([
          fetchSchoolYearSummary(schoolYear),
          fetchSchoolYearPromotionPreview(schoolYear),
          fetchSchoolYearParentBalances(schoolYear),
        ])
        if (!cancelled) {
          setSummary(nextSummary)
          setPromotionPreview(nextPromotion)
          setParentBalances(nextBalances)
        }
      } catch (loadError) {
        if (!cancelled) setError(normalizeApiError(loadError, 'Unable to load school year detail.'))
      } finally {
        if (!cancelled) setLoading(false)
      }
    })()

    return () => {
      cancelled = true
    }
  }, [schoolYear])

  const totals = summary?.totals
  const promotion = promotionPreview?.summary
  const balances = parentBalances?.summary

  const rows = useMemo(() => parentBalances?.rows.slice(0, 25) ?? [], [parentBalances])

  return (
    <div className="container-fluid py-4">
      <nav aria-label="breadcrumb">
        <ol className="breadcrumb">
          <li className="breadcrumb-item"><Link to="/app/home">Home</Link></li>
          <li className="breadcrumb-item"><Link to="/app/admin/school-years">School years</Link></li>
          <li className="breadcrumb-item active" aria-current="page">Summary</li>
        </ol>
      </nav>

      <div className="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4">
        <div>
          <h1 className="h3 mb-1">School Year Summary</h1>
          <p className="text-muted mb-0">
            Academic promotion, parent-level balance exposure, and closure readiness in one place.
          </p>
        </div>
        {summary?.school_year ? <SchoolYearStatusBadge status={summary.school_year.status} /> : null}
      </div>

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

      {summary ? (
        <>
          <div className="row g-3 mb-4">
            <div className="col-md-6 col-xl-3">
              <div className="card shadow-sm h-100"><div className="card-body">
                <div className="small text-muted text-uppercase">Students considered</div>
                <div className="display-6">{totals?.students_considered ?? 0}</div>
              </div></div>
            </div>
            <div className="col-md-6 col-xl-3">
              <div className="card shadow-sm h-100"><div className="card-body">
                <div className="small text-muted text-uppercase">Students blocked</div>
                <div className="display-6">{totals?.students_blocked ?? 0}</div>
              </div></div>
            </div>
            <div className="col-md-6 col-xl-3">
              <div className="card shadow-sm h-100"><div className="card-body">
                <div className="small text-muted text-uppercase">Unpaid carryover parents</div>
                <div className="display-6">{totals?.parents_with_positive_balance ?? totals?.parents_with_balances ?? 0}</div>
              </div></div>
            </div>
            <div className="col-md-6 col-xl-3">
              <div className="card shadow-sm h-100"><div className="card-body">
                <div className="small text-muted text-uppercase">Net transfer impact</div>
                <div className="display-6">${formatMoney(totals?.net_balance_impact ?? totals?.net_balance_to_transfer)}</div>
              </div></div>
            </div>
          </div>

          <div className="row g-4">
            <div className="col-xl-5">
              <div className="card shadow-sm h-100">
                <div className="card-body">
                  <h2 className="h5">Promotion summary</h2>
                  <dl className="row mb-0 small">
                    <dt className="col-6">Promote</dt><dd className="col-6 text-end">{promotion?.promote ?? 0}</dd>
                    <dt className="col-6">Repeat</dt><dd className="col-6 text-end">{promotion?.repeat ?? 0}</dd>
                    <dt className="col-6">Graduate</dt><dd className="col-6 text-end">{promotion?.graduate ?? 0}</dd>
                    <dt className="col-6">Withdraw</dt><dd className="col-6 text-end">{promotion?.withdraw ?? 0}</dd>
                    <dt className="col-6">Missing decision</dt><dd className="col-6 text-end">{promotion?.hold ?? 0}</dd>
                  </dl>
                </div>
              </div>
            </div>
            <div className="col-xl-7">
              <div className="card shadow-sm h-100">
                <div className="card-body">
                  <h2 className="h5">Parent balance preview</h2>
                  <div className="small text-muted mb-3">
                    {balances?.parents_with_positive_balance ?? 0} parents with unpaid balances,
                    {balances?.parents_with_credit_balance ?? 0} parents with credits,
                    net ${formatMoney(balances?.net_balance_impact ?? balances?.net_balance_to_transfer)}.
                  </div>
                  <div className="table-responsive">
                    <table className="table table-sm align-middle mb-0">
                      <thead><tr><th>Parent</th><th>Students</th><th className="text-end">Unpaid</th><th className="text-end">Credits</th><th className="text-end">Net</th></tr></thead>
                      <tbody>
                        {rows.length === 0 ? (
                          <tr><td colSpan={5} className="text-muted">No balance rows found.</td></tr>
                        ) : rows.map((row) => (
                          <tr key={row.parent_id}>
                            <td>{row.parent_name || `Parent #${row.parent_id}`}</td>
                            <td>{row.student_names?.join(', ') || '—'}</td>
                            <td className="text-end">${formatMoney(row.positive_unpaid_balance ?? row.amount_to_transfer)}</td>
                            <td className="text-end">${formatMoney(row.credit_balance)}</td>
                            <td className="text-end">${formatMoney(row.net_balance)}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </>
      ) : null}
    </div>
  )
}
