import { useEffect, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import {
  fetchNotificationsDeleted,
  restoreDeletedNotification,
  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 NotificationsDeletedPage() {
  const [searchParams] = useSearchParams()
  const schoolYear = searchParams.get('school_year') ?? undefined
  const semester = searchParams.get('semester') ?? undefined

  const [rows, setRows] = useState<AdminNotificationRow[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [msg, setMsg] = useState<string | null>(null)
  const [busyId, setBusyId] = useState<number | string | null>(null)

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

  useEffect(() => {
    load()
  }, [schoolYear, semester])

  async function onRestore(id: number | string) {
    setBusyId(id)
    setMsg(null)
    try {
      await restoreDeletedNotification(id)
      setMsg('Notification restored.')
      load()
    } catch (e: unknown) {
      setMsg(e instanceof ApiHttpError ? e.message : 'Restore failed.')
    } finally {
      setBusyId(null)
    }
  }

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

      {msg ? (
        <div
          className={`alert ${msg.includes('fail') ? 'alert-warning' : 'alert-success'}`}
          role="status"
        >
          {msg}
        </div>
      ) : null}
      {error ? <div className="alert alert-danger">{error}</div> : null}

      <div className="table-responsive">
        <table className="table table-striped table-bordered align-middle">
          <thead className="table-dark">
            <tr>
              <th>#</th>
              <th>Title</th>
              <th>Message</th>
              <th>Priority</th>
              <th>Scheduled At</th>
              <th>Expires At</th>
              <th>Deleted At</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td colSpan={8} className="text-center text-muted">
                  Loading deleted notifications…
                </td>
              </tr>
            ) : rows.length === 0 ? (
              <tr>
                <td colSpan={8} className="text-center text-muted">
                  No deleted notifications found.
                </td>
              </tr>
            ) : (
              rows.map((entry, index) => (
                <tr key={entry.id ?? index}>
                  <td>{index + 1}</td>
                  <td>{entry.title ?? '—'}</td>
                  <td style={{ maxWidth: 320 }}>{entry.message ?? '—'}</td>
                  <td>{entry.priority ?? '—'}</td>
                  <td>{formatDt(entry.scheduled_at)}</td>
                  <td>{entry.expires_at ? formatDt(entry.expires_at) : 'No expiry'}</td>
                  <td>{formatDt(entry.deleted_at)}</td>
                  <td>
                    {entry.id != null ? (
                      <button
                        type="button"
                        className="btn btn-sm btn-success"
                        disabled={busyId === entry.id}
                        onClick={() => onRestore(entry.id as number | string)}
                      >
                        Restore
                      </button>
                    ) : (
                      '—'
                    )}
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  )
}
