import { type FormEvent, useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { fetchPaymentNotificationLogs, type PaymentNotificationLogRow } from '../../api/paymentManagement'
import { AcademicFilterBar } from '../discounts/AcademicFilterBar'

function fmtBalance(row: PaymentNotificationLogRow): string {
  const v = row.balance_snapshot
  if (v == null) return ''
  const n = Number(v)
  return `$${Number.isFinite(n) ? n.toFixed(2) : String(v)}`
}

export function PaymentNotificationManagementPage() {
  const [searchParams, setSearchParams] = useSearchParams()
  const schoolYear = searchParams.get('school_year') ?? undefined
  const semester = searchParams.get('semester') ?? undefined
  const from = searchParams.get('from') ?? ''
  const to = searchParams.get('to') ?? ''
  const type = searchParams.get('type') ?? ''

  const [logs, setLogs] = useState<PaymentNotificationLogRow[]>([])
  const [parentsById, setParentsById] = useState<Record<string, string>>({})
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    setLoading(true)
    setError(null)
    fetchPaymentNotificationLogs({
      from: from || undefined,
      to: to || undefined,
      type: type || undefined,
      school_year: schoolYear,
      semester: semester || undefined,
    })
      .then((d) => {
        setLogs(d.logs ?? [])
        setParentsById(d.parentsById ?? {})
      })
      .catch((e: unknown) =>
        setError(e instanceof ApiHttpError ? e.message : 'Could not load notification logs.'),
      )
      .finally(() => setLoading(false))
  }, [from, to, type, schoolYear, semester])

  function onFilterSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    const fd = new FormData(e.currentTarget)
    const next = new URLSearchParams(searchParams)
    const f = String(fd.get('from') ?? '')
    const t = String(fd.get('to') ?? '')
    const ty = String(fd.get('type') ?? '')
    if (f) next.set('from', f)
    else next.delete('from')
    if (t) next.set('to', t)
    else next.delete('to')
    if (ty) next.set('type', ty)
    else next.delete('type')
    setSearchParams(next)
  }

  function setQuickRange(days: number) {
    const end = new Date()
    const start = new Date()
    start.setDate(start.getDate() - days)
    const iso = (d: Date) => d.toISOString().slice(0, 19).replace('T', ' ')
    const next = new URLSearchParams(searchParams)
    next.set('from', iso(start))
    next.set('to', iso(end))
    setSearchParams(next)
  }

  return (
    <div className="container-fluid py-3">
      <div className="d-flex align-items-center gap-2 mb-3">
        <h1 className="h4 mb-0">Payment Notification Management</h1>
        <span className="text-muted small">Review monthly reminder emails sent to parents.</span>
      </div>

      <AcademicFilterBar />

      <div className="card mb-3">
        <div className="card-body">
          <form className="row g-2 align-items-end" onSubmit={onFilterSubmit}>
            <div className="col-md-3">
              <label className="form-label" htmlFor="from">
                From
              </label>
              <input
                id="from"
                name="from"
                type="text"
                className="form-control"
                placeholder="YYYY-MM-DD HH:MM:SS"
                defaultValue={from}
              />
            </div>
            <div className="col-md-3">
              <label className="form-label" htmlFor="to">
                To
              </label>
              <input
                id="to"
                name="to"
                type="text"
                className="form-control"
                placeholder="YYYY-MM-DD HH:MM:SS"
                defaultValue={to}
              />
            </div>
            <div className="col-md-2">
              <label className="form-label" htmlFor="type">
                Type
              </label>
              <select id="type" name="type" className="form-select" defaultValue={type}>
                <option value="">All</option>
                <option value="no_payment">No Payment</option>
                <option value="installment">Installment</option>
              </select>
            </div>
            <div className="col-md-4 d-flex gap-2 flex-wrap">
              <button className="btn btn-primary" type="submit">
                Filter
              </button>
              <button type="button" className="btn btn-outline-secondary" onClick={() => setQuickRange(30)}>
                Last 30 days
              </button>
              <Link className="btn btn-outline-dark" to="/app/administrator/payment/notification-management">
                Reset
              </Link>
            </div>
          </form>
        </div>
      </div>

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

      <div className="card">
        <div className="card-body">
          <div className="table-responsive">
            <table className="table table-sm align-middle">
              <thead>
                <tr>
                  <th>Sent At</th>
                  <th>Parent</th>
                  <th>Type</th>
                  <th>To</th>
                  <th>CC</th>
                  <th>Balance</th>
                  <th>Status</th>
                  <th>Subject</th>
                </tr>
              </thead>
              <tbody>
                {logs.length === 0 && !loading ? (
                  <tr>
                    <td colSpan={8} className="text-center text-muted py-4">
                      No notifications found.
                    </td>
                  </tr>
                ) : (
                  logs.map((r, i) => {
                    const pid = String(r.parent_id ?? '')
                    const parentLabel = parentsById[pid] ?? `#${pid}`
                    const sentAt = String(r.sent_at ?? r.created_at ?? '')
                    const ok = String(r.status ?? '') === 'sent'
                    return (
                      <tr key={i}>
                        <td>{sentAt}</td>
                        <td>{parentLabel}</td>
                        <td>
                          <span className="badge bg-info text-dark">{String(r.type ?? '')}</span>
                        </td>
                        <td>{String(r.to_email ?? '')}</td>
                        <td>{String(r.cc_email ?? '')}</td>
                        <td>{fmtBalance(r)}</td>
                        <td>
                          {ok ? (
                            <span className="badge bg-success">Sent</span>
                          ) : (
                            <span className="badge bg-danger" title={String(r.error_message ?? '')}>
                              Failed
                            </span>
                          )}
                        </td>
                        <td>{String(r.subject ?? '')}</td>
                      </tr>
                    )
                  })
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  )
}
