import { useEffect, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import {
  fetchNotificationsActive,
  type AdminNotificationRow,
} from '../../api/paymentManagement'
import { AcademicFilterBar } from '../discounts/AcademicFilterBar'

function formatDt(value: string | undefined): string {
  if (!value) return '—'
  const date = new Date(String(value).replace(' ', 'T'))
  if (Number.isNaN(date.valueOf())) return value
  const pad = (n: number) => String(n).padStart(2, '0')
  const datePart = `${pad(date.getMonth() + 1)}-${pad(date.getDate())}-${date.getFullYear()}`
  const hasTime = /[T ]\d{2}:\d{2}/.test(String(value))
  if (!hasTime) return datePart
  return `${datePart} ${pad(date.getHours())}:${pad(date.getMinutes())}`
}

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

  const [targetGroup, setTargetGroup] = useState('')
  const [rows, setRows] = useState<AdminNotificationRow[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  function load(tg: string) {
    setLoading(true)
    setError(null)
    fetchNotificationsActive({
      target_group: tg || undefined,
      school_year: schoolYear,
      semester: semester || undefined,
    })
      .then((d) => setRows(d.notifications ?? []))
      .catch((e: unknown) =>
        setError(e instanceof ApiHttpError ? e.message : 'Unable to load notifications.'),
      )
      .finally(() => setLoading(false))
  }

  useEffect(() => {
    load('')
    // eslint-disable-next-line react-hooks/exhaustive-deps -- initial load only; filters applied via buttons
  }, [schoolYear, semester])

  return (
    <div className="container-fluid px-0 mt-4">
      <h2 className="text-center mt-4 mb-3">Active Notifications</h2>
      <AcademicFilterBar />

      <div className="d-flex align-items-center gap-2 mb-3 flex-wrap">
        <label htmlFor="targetGroupInput" className="form-label mb-0">
          Target Group:
        </label>
        <input
          id="targetGroupInput"
          type="text"
          className="form-control w-auto"
          placeholder="All groups"
          value={targetGroup}
          onChange={(e) => setTargetGroup(e.target.value)}
        />
        <button type="button" className="btn btn-outline-primary" onClick={() => load(targetGroup.trim())}>
          Apply
        </button>
        <button
          type="button"
          className="btn btn-outline-secondary"
          onClick={() => {
            setTargetGroup('')
            load('')
          }}
        >
          Reset
        </button>
      </div>

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

      <div className="table-responsive">
        <table className="table table-striped table-bordered align-middle w-100">
          <thead className="table-dark">
            <tr>
              <th>#</th>
              <th>Title</th>
              <th>Message</th>
              <th>Priority</th>
              <th>Target Group</th>
              <th>Scheduled At</th>
              <th>Expires At</th>
              <th>Created At</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td colSpan={8} className="text-center text-muted">
                  Loading notifications…
                </td>
              </tr>
            ) : rows.length === 0 ? (
              <tr>
                <td colSpan={8} className="text-center text-muted">
                  No active notifications found.
                </td>
              </tr>
            ) : (
              rows.map((entry, index) => (
                <tr key={entry.id ?? index} className={entry.isExpired ? 'table-danger' : undefined}>
                  <td>{index + 1}</td>
                  <td>{entry.title ?? '—'}</td>
                  <td style={{ maxWidth: 320 }}>{entry.message ?? '—'}</td>
                  <td>{entry.priority ?? '—'}</td>
                  <td>{entry.target_group ?? '—'}</td>
                  <td>{formatDt(entry.scheduled_at)}</td>
                  <td>{entry.expires_at ? formatDt(entry.expires_at) : 'No expiry'}</td>
                  <td>{formatDt(entry.created_at)}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  )
}
