import { useEffect, useMemo, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import {
  fetchSchoolYearBalanceTransferReport,
  fetchSchoolYearClosingReport,
  type SchoolYearBalanceTransferReport,
  type SchoolYearClosingReport,
} from '../../api/schoolYears'

type ReportType = 'closing' | 'balance-transfers'

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,
  })
}

function formatDateTime(value: string | null | undefined): string {
  if (!value) return '—'
  const parsed = new Date(value)
  if (Number.isNaN(parsed.getTime())) return value
  return parsed.toLocaleString()
}

function ClosingReportView({ report }: { report: SchoolYearClosingReport }) {
  const totals = report.totals ?? {}

  return (
    <div className="card shadow-sm">
      <div className="card-body">
        <h2 className="h5 mb-3">Closing Report</h2>
        <dl className="row small mb-4">
          <dt className="col-md-3">Old school year</dt>
          <dd className="col-md-9">{report.old_school_year?.name ?? '—'}</dd>
          <dt className="col-md-3">New school year</dt>
          <dd className="col-md-9">{report.new_school_year?.name ?? '—'}</dd>
          <dt className="col-md-3">Closed by</dt>
          <dd className="col-md-9">{report.closed_by ?? '—'}</dd>
          <dt className="col-md-3">Closed at</dt>
          <dd className="col-md-9">{formatDateTime(report.closed_at)}</dd>
          <dt className="col-md-3">Audit reference</dt>
          <dd className="col-md-9">{report.audit_reference ?? '—'}</dd>
        </dl>

        <div className="row g-3 mb-4">
          <div className="col-md-4"><div className="border rounded p-3 h-100"><div className="small text-muted">Promoted</div><div className="h4 mb-0">{totals.students_promoted ?? 0}</div></div></div>
          <div className="col-md-4"><div className="border rounded p-3 h-100"><div className="small text-muted">Repeated</div><div className="h4 mb-0">{totals.students_repeated ?? 0}</div></div></div>
          <div className="col-md-4"><div className="border rounded p-3 h-100"><div className="small text-muted">Graduated</div><div className="h4 mb-0">{totals.students_graduated ?? 0}</div></div></div>
          <div className="col-md-4"><div className="border rounded p-3 h-100"><div className="small text-muted">Parents with unpaid balances</div><div className="h4 mb-0">{totals.parents_with_unpaid_balances ?? 0}</div></div></div>
          <div className="col-md-4"><div className="border rounded p-3 h-100"><div className="small text-muted">Unpaid transferred</div><div className="h4 mb-0">${formatMoney(totals.total_unpaid_balance_transferred)}</div></div></div>
          <div className="col-md-4"><div className="border rounded p-3 h-100"><div className="small text-muted">Credits carried or reported</div><div className="h4 mb-0">${formatMoney(totals.total_credit_carried_or_reported ?? totals.total_credit_transferred)}</div></div></div>
          <div className="col-md-4"><div className="border rounded p-3 h-100"><div className="small text-muted">Net balance impact</div><div className="h4 mb-0">${formatMoney(totals.net_balance_impact)}</div></div></div>
        </div>

        {report.warnings?.length ? (
          <div className="alert alert-warning mb-0">
            <div className="fw-semibold mb-2">Warnings</div>
            <ul className="mb-0">
              {report.warnings.map((warning) => <li key={warning}>{warning}</li>)}
            </ul>
          </div>
        ) : null}
      </div>
    </div>
  )
}

function BalanceTransfersView({ report }: { report: SchoolYearBalanceTransferReport }) {
  const rows = report.rows ?? []

  return (
    <div className="card shadow-sm">
      <div className="card-body">
        <h2 className="h5 mb-3">Parent Balance Transfer Report</h2>
        <div className="row g-3 mb-4">
          <div className="col-md-4"><div className="border rounded p-3"><div className="small text-muted">Parents</div><div className="h4 mb-0">{report.summary?.parent_count ?? rows.length}</div></div></div>
          <div className="col-md-4"><div className="border rounded p-3"><div className="small text-muted">Total transferred</div><div className="h4 mb-0">${formatMoney(report.summary?.total_transferred)}</div></div></div>
          <div className="col-md-4"><div className="border rounded p-3"><div className="small text-muted">Total credit</div><div className="h4 mb-0">${formatMoney(report.summary?.total_credit)}</div></div></div>
        </div>

        <div className="table-responsive">
          <table className="table table-sm align-middle">
            <thead>
              <tr>
                <th>Parent</th>
                <th>Old year</th>
                <th>New year</th>
                <th>Source invoices</th>
                <th className="text-end">Old unpaid</th>
                <th>New invoice</th>
                <th>Status</th>
                <th>Transfer date</th>
                <th>Created by</th>
              </tr>
            </thead>
            <tbody>
              {rows.length === 0 ? (
                <tr><td colSpan={9} className="text-muted">No transfer rows found.</td></tr>
              ) : rows.map((row) => (
                <tr key={`${row.parent_id}-${row.new_old_balance_invoice_id ?? 'none'}`}>
                  <td>{row.parent_name || `Parent #${row.parent_id}`}</td>
                  <td>{row.old_school_year ?? '—'}</td>
                  <td>{row.new_school_year ?? '—'}</td>
                  <td>{row.source_invoice_ids?.join(', ') || '—'}</td>
                  <td className="text-end">${formatMoney(row.old_unpaid_amount)}</td>
                  <td>{row.new_old_balance_invoice_id ?? '—'}</td>
                  <td>{row.transfer_status ?? '—'}</td>
                  <td>{formatDateTime(row.transfer_date)}</td>
                  <td>{row.created_by ?? '—'}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}

export function SchoolYearReportsPage({ reportType }: { reportType: ReportType }) {
  const [searchParams] = useSearchParams()
  const schoolYear = searchParams.get('school_year')?.trim() ?? ''
  const [closingReport, setClosingReport] = useState<SchoolYearClosingReport | null>(null)
  const [balanceReport, setBalanceReport] = useState<SchoolYearBalanceTransferReport | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const title = useMemo(
    () => reportType === 'closing' ? 'Closing Report' : 'Balance Transfer Report',
    [reportType],
  )

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

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

    ;(async () => {
      try {
        if (reportType === 'closing') {
          const report = await fetchSchoolYearClosingReport(schoolYear)
          if (!cancelled) setClosingReport(report)
        } else {
          const report = await fetchSchoolYearBalanceTransferReport(schoolYear)
          if (!cancelled) setBalanceReport(report)
        }
      } catch (loadError) {
        if (!cancelled) setError(normalizeApiError(loadError, `Unable to load ${title.toLowerCase()}.`))
      } finally {
        if (!cancelled) setLoading(false)
      }
    })()

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

  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">{title}</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">{title}</h1>
          <p className="text-muted mb-0">
            Report downloads must be served by authorized backend routes with private file storage.
            This screen only displays records returned by those routes.
          </p>
        </div>
        <Link className="btn btn-outline-secondary btn-sm" to={`/app/admin/school-years/summary?school_year=${encodeURIComponent(schoolYear)}`}>
          Back to summary
        </Link>
      </div>

      {error ? <div className="alert alert-danger">{error}</div> : null}
      {loading ? <p className="text-muted">Loading report…</p> : null}
      {closingReport ? <ClosingReportView report={closingReport} /> : null}
      {balanceReport ? <BalanceTransfersView report={balanceReport} /> : null}
    </div>
  )
}
