import { useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import {
  fetchParentPaymentsForModal,
  fetchUnpaidParents,
  sendPaymentReminders,
  type ParentPaymentsModalRow,
  type UnpaidParentRow,
} from '../../api/paymentManagement'
import { AcademicFilterBar } from '../discounts/AcademicFilterBar'

/** Outstanding balances — `GET /api/v1/administrator/payments/unpaid-parents`, reminders via `POST .../notifications/send`, payments modal `GET .../parent/:id/payments-list` (JWT). SPA: `/app/payment/unpaid-parents`. */

function fmtMoney(n: unknown): string {
  const v = Number(n)
  return Number.isFinite(v) ? v.toFixed(2) : '0.00'
}

function PaymentsModal({
  open,
  onClose,
  parentId,
  parentName,
}: {
  open: boolean
  onClose: () => void
  parentId: number | null
  parentName: string
}) {
  const [rows, setRows] = useState<ParentPaymentsModalRow[]>([])
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (!open || parentId == null) return
    setLoading(true)
    fetchParentPaymentsForModal(parentId)
      .then((d) => setRows(d.payments ?? []))
      .catch(() => setRows([]))
      .finally(() => setLoading(false))
  }, [open, parentId])

  if (!open) return null

  return (
    <div className="modal show d-block" tabIndex={-1} style={{ background: 'rgba(0,0,0,.45)' }}>
      <div className="modal-dialog modal-lg modal-dialog-scrollable">
        <div className="modal-content">
          <div className="modal-header">
            <h5 className="modal-title">
              Payments — {parentName}
              {parentId != null ? ` (#${parentId})` : ''}
            </h5>
            <button type="button" className="btn-close" aria-label="Close" onClick={onClose} />
          </div>
          <div className="modal-body">
            {loading ? (
              <p className="text-muted">Loading…</p>
            ) : (
              <div className="table-responsive">
                <table className="table table-sm align-middle mb-0">
                  <thead className="table-light">
                    <tr>
                      <th>Date</th>
                      <th>Invoice</th>
                      <th className="text-end">Paid</th>
                      <th className="text-end">Balance</th>
                      <th>Method</th>
                      <th>Status</th>
                    </tr>
                  </thead>
                  <tbody>
                    {rows.length === 0 ? (
                      <tr>
                        <td colSpan={6} className="text-center text-muted py-4">
                          No payment
                        </td>
                      </tr>
                    ) : (
                      rows.map((p, idx) => (
                        <tr key={idx}>
                          <td>{String(p.payment_date ?? '')}</td>
                          <td>
                            {String(p.invoice_number ?? '').trim() ||
                              (p.invoice_id != null ? `#${p.invoice_id}` : '')}
                          </td>
                          <td className="text-end">${fmtMoney(p.paid_amount)}</td>
                          <td className="text-end">${fmtMoney(p.balance)}</td>
                          <td>{String(p.payment_method ?? '')}</td>
                          <td>{String(p.status ?? '')}</td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}

export function UnpaidParentsPage() {
  const [searchParams] = useSearchParams()
  const schoolYear = searchParams.get('school_year') ?? ''

  const [rows, setRows] = useState<UnpaidParentRow[]>([])
  const [yearLabel, setYearLabel] = useState(schoolYear)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [msg, setMsg] = useState<string | null>(null)
  const [modalOpen, setModalOpen] = useState(false)
  const [modalParentId, setModalParentId] = useState<number | null>(null)
  const [modalName, setModalName] = useState('')

  useEffect(() => {
    setLoading(true)
    setError(null)
    fetchUnpaidParents({
      school_year: schoolYear || undefined,
      semester: searchParams.get('semester') ?? undefined,
    })
      .then((d) => {
        setRows(d.rows ?? [])
        setYearLabel(String(d.school_year ?? schoolYear))
      })
      .catch((e: unknown) =>
        setError(e instanceof ApiHttpError ? e.message : 'Could not load unpaid parents.'),
      )
      .finally(() => setLoading(false))
  }, [schoolYear, searchParams])

  let sumEvent = 0
  let sumInv = 0
  let sumPaid = 0
  let sumDisc = 0
  let sumInst = 0
  let sumBal = 0
  for (const r of rows) {
    sumEvent += Number(r.event_fees ?? 0)
    sumInv += Number(r.total_invoice ?? 0)
    sumPaid += Number(r.total_paid ?? 0)
    sumDisc += Number(r.total_discount ?? 0)
    sumInst += Number(r.installment_amount ?? 0)
    sumBal += Number(r.total_balance ?? 0)
  }

  async function onSendAll() {
    if (!confirm('Send reminders to all listed parents?')) return
    setMsg(null)
    try {
      await sendPaymentReminders({
        school_year: yearLabel || schoolYear,
        return_to: `${window.location.pathname}${window.location.search}`,
      })
      setMsg('Reminders queued.')
    } catch (e: unknown) {
      setMsg(e instanceof ApiHttpError ? e.message : 'Send failed.')
    }
  }

  async function onSendOne(parentId: number | string) {
    setMsg(null)
    try {
      await sendPaymentReminders({
        school_year: yearLabel || schoolYear,
        parent_id: parentId,
        return_to: `${window.location.pathname}${window.location.search}`,
      })
      setMsg('Reminder sent.')
    } catch (e: unknown) {
      setMsg(e instanceof ApiHttpError ? e.message : 'Send failed.')
    }
  }

  return (
    <div className="container-fluid py-3">
      <div className="d-flex align-items-center gap-2 mb-3">
        <h1 className="h5 mb-0">Parents With Outstanding Balance</h1>
        <span className="text-muted small">Balance is summed across invoices for the selected school year.</span>
      </div>

      <AcademicFilterBar />

      {msg ? <div className="alert alert-info">{msg}</div> : null}
      {error ? <div className="alert alert-danger">{error}</div> : null}

      <div className="card">
        <div className="card-body">
          <div className="d-flex justify-content-end mb-2 gap-2">
            <button type="button" className="btn btn-primary btn-sm" onClick={onSendAll}>
              Send Reminders (All)
            </button>
          </div>

          <div className="table-responsive">
            <table className="table table-sm align-middle">
              <thead>
                <tr>
                  <th>Parent</th>
                  <th className="text-center">Nbr of Installements</th>
                  <th>Type</th>
                  <th className="text-end">Event Fees</th>
                  <th className="text-end">Invoice Amount</th>
                  <th className="text-end">Applied Discount</th>
                  <th className="text-end">Paid Amount</th>
                  <th className="text-center">Remaining Inst.</th>
                  <th className="text-end">Inst Amount</th>
                  <th>Installment</th>
                  <th className="text-end">Outstanding Balance</th>
                  <th>Next Installment</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {loading ? (
                  <tr>
                    <td colSpan={13} className="text-center text-muted py-4">
                      Loading…
                    </td>
                  </tr>
                ) : rows.length === 0 ? (
                  <tr>
                    <td colSpan={13} className="text-center text-muted py-4">
                      No parents with outstanding balance.
                    </td>
                  </tr>
                ) : (
                  rows.map((r) => {
                    const pid = Number(r.parent_id ?? 0)
                    const typ = String(r.type ?? '') === 'no_payment' ? 'no payment' : 'installment'
                    return (
                      <tr key={pid}>
                        <td>
                          <Link
                            to={`/app/administrator/family?guardian_id=${pid}`}
                            className="text-decoration-none"
                          >
                            {String(r.parent_name ?? '')}
                          </Link>
                          <small className="text-muted ms-1">#{pid}</small>
                        </td>
                        <td className="text-center">{Number(r.payment_count ?? 0)}</td>
                        <td>
                          <span
                            className={`badge text-capitalize ${typ === 'no payment' ? 'bg-danger' : 'bg-success'}`}
                          >
                            {typ}
                          </span>
                        </td>
                        <td className="text-end">${fmtMoney(r.event_fees)}</td>
                        <td className="text-end">${fmtMoney(r.total_invoice)}</td>
                        <td className="text-end text-success">-${fmtMoney(r.total_discount)}</td>
                        <td className="text-end">${fmtMoney(r.total_paid)}</td>
                        <td className="text-center">{Number(r.remaining_installments ?? 0)}</td>
                        <td className="text-end">${fmtMoney(r.installment_amount)}</td>
                        <td>
                          {r.has_installment ? (
                            <span className="badge bg-success">Yes</span>
                          ) : (
                            <span className="badge bg-danger">No</span>
                          )}
                        </td>
                        <td className="text-end">${fmtMoney(r.total_balance)}</td>
                        <td>{String(r.next_installment ?? '')}</td>
                        <td className="text-nowrap">
                          <button
                            type="button"
                            className="btn btn-outline-secondary btn-sm me-1"
                            onClick={() => {
                              setModalParentId(pid)
                              setModalName(String(r.parent_name ?? ''))
                              setModalOpen(true)
                            }}
                          >
                            Payments
                          </button>
                          <button
                            type="button"
                            className="btn btn-outline-primary btn-sm"
                            onClick={() => onSendOne(pid)}
                          >
                            Send Reminder
                          </button>
                        </td>
                      </tr>
                    )
                  })
                )}
              </tbody>
              {rows.length > 0 ? (
                <tfoot>
                  <tr>
                    <th colSpan={3} className="text-end">
                      Totals:
                    </th>
                    <th className="text-end">${sumEvent.toFixed(2)}</th>
                    <th className="text-end">${sumInv.toFixed(2)}</th>
                    <th className="text-end text-success">-${sumDisc.toFixed(2)}</th>
                    <th className="text-end">${sumPaid.toFixed(2)}</th>
                    <th className="text-center">&mdash;</th>
                    <th className="text-end">${sumInst.toFixed(2)}</th>
                    <th />
                    <th className="text-end">${sumBal.toFixed(2)}</th>
                    <th colSpan={2} />
                  </tr>
                </tfoot>
              ) : null}
            </table>
          </div>
        </div>
      </div>

      <PaymentsModal
        open={modalOpen}
        onClose={() => setModalOpen(false)}
        parentId={modalParentId}
        parentName={modalName}
      />
    </div>
  )
}
