'use client'

import { useEffect, useState } from 'react'
import { ADMIN_API_BASE } from '@/lib/api'

interface NotificationItem {
  id: string
  type: string
  title: string
  body: string
  channel: string
  status: string
  locale: string
  sentAt: string | null
  createdAt: string
  company: { name: string } | null
  companyId: string | null
  renterId: string | null
}

interface Paginated {
  data: NotificationItem[]
  total: number
  page: number
  pageSize: number
}

const CHANNELS = ['EMAIL', 'SMS', 'WHATSAPP', 'IN_APP', 'PUSH']
const STATUSES = ['PENDING', 'SENT', 'DELIVERED', 'FAILED', 'READ']

const CHANNEL_BADGE: Record<string, string> = {
  EMAIL:    'text-sky-400 bg-sky-950/40',
  SMS:      'text-emerald-400 bg-emerald-950/40',
  WHATSAPP: 'text-teal-400 bg-teal-950/40',
  IN_APP:   'text-violet-400 bg-violet-950/40',
  PUSH:     'text-orange-400 bg-orange-950/40',
}

const STATUS_BADGE: Record<string, string> = {
  PENDING:   'text-yellow-400 bg-yellow-950/40',
  SENT:      'text-emerald-400 bg-emerald-950/40',
  DELIVERED: 'text-emerald-400 bg-emerald-950/40',
  FAILED:    'text-red-400 bg-red-950/40',
  READ:      'text-zinc-400 bg-zinc-800',
}

export default function AdminNotificationsPage() {
  const [result, setResult] = useState<Paginated | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [filterChannel, setFilterChannel] = useState('')
  const [filterStatus, setFilterStatus] = useState('')
  const [filterCompany, setFilterCompany] = useState('')
  const [page, setPage] = useState(1)

  function load(p: number) {
    setLoading(true)
    setError(null)
    const params = new URLSearchParams({ page: String(p), pageSize: '50' })
    if (filterChannel) params.set('channel', filterChannel)
    if (filterStatus)  params.set('status',  filterStatus)
    if (filterCompany) params.set('companyId', filterCompany)

    fetch(`${ADMIN_API_BASE}/admin/notifications?${params.toString()}`, {
      credentials: 'include',
      cache: 'no-store',
    })
      .then((r) => r.json())
      .then((json) => setResult(json.data ?? null))
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false))
  }

  useEffect(() => {
    setPage(1)
    load(1)
  }, [filterChannel, filterStatus, filterCompany])

  function goToPage(p: number) {
    setPage(p)
    load(p)
  }

  const totalPages = result ? Math.ceil(result.total / result.pageSize) : 0

  return (
    <div className="shell py-8 space-y-6">
      <div className="flex flex-wrap items-start justify-between gap-4">
        <div>
          <p className="text-xs uppercase tracking-[0.2em] text-orange-400">Platform</p>
          <h1 className="mt-1 text-3xl font-black">Notifications</h1>
          <p className="mt-1 text-sm text-zinc-400">
            Full audit log of every notification sent across all companies.
          </p>
        </div>
        {result && (
          <span className="rounded-full bg-zinc-800 px-3 py-1 text-sm text-zinc-300">
            {result.total.toLocaleString()} total
          </span>
        )}
      </div>

      {/* Filters */}
      <div className="flex flex-wrap items-center gap-3">
        <select
          value={filterChannel}
          onChange={(e) => setFilterChannel(e.target.value)}
          className="rounded-xl border border-zinc-700 bg-zinc-800 px-3 py-2 text-sm text-zinc-100 focus:outline-none focus:ring-2 focus:ring-orange-500"
        >
          <option value="">All channels</option>
          {CHANNELS.map((ch) => <option key={ch} value={ch}>{ch}</option>)}
        </select>
        <select
          value={filterStatus}
          onChange={(e) => setFilterStatus(e.target.value)}
          className="rounded-xl border border-zinc-700 bg-zinc-800 px-3 py-2 text-sm text-zinc-100 focus:outline-none focus:ring-2 focus:ring-orange-500"
        >
          <option value="">All statuses</option>
          {STATUSES.map((s) => <option key={s} value={s}>{s}</option>)}
        </select>
      </div>

      {error && <div className="panel p-4 text-sm text-red-400">{error}</div>}

      <div className="panel overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-zinc-800">
                <th className="px-5 py-3 text-left text-xs font-medium uppercase tracking-wider text-zinc-500">Date</th>
                <th className="px-5 py-3 text-left text-xs font-medium uppercase tracking-wider text-zinc-500">Company</th>
                <th className="px-5 py-3 text-left text-xs font-medium uppercase tracking-wider text-zinc-500">Event</th>
                <th className="px-5 py-3 text-left text-xs font-medium uppercase tracking-wider text-zinc-500">Channel</th>
                <th className="px-5 py-3 text-left text-xs font-medium uppercase tracking-wider text-zinc-500">Title</th>
                <th className="px-5 py-3 text-left text-xs font-medium uppercase tracking-wider text-zinc-500">Status</th>
                <th className="px-5 py-3 text-left text-xs font-medium uppercase tracking-wider text-zinc-500">Sent at</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-zinc-800/60">
              {loading ? (
                <tr><td colSpan={7} className="px-5 py-12 text-center text-zinc-500">Loading…</td></tr>
              ) : !result || result.data.length === 0 ? (
                <tr><td colSpan={7} className="px-5 py-12 text-center text-zinc-500">No notifications found.</td></tr>
              ) : result.data.map((item) => (
                <tr key={item.id} className="hover:bg-zinc-800/30 transition-colors">
                  <td className="whitespace-nowrap px-5 py-3 text-xs text-zinc-500">
                    {new Date(item.createdAt).toLocaleString()}
                  </td>
                  <td className="whitespace-nowrap px-5 py-3 text-xs text-zinc-300">
                    {item.company?.name ?? (item.companyId ? item.companyId.slice(0, 10) + '…' : '—')}
                  </td>
                  <td className="whitespace-nowrap px-5 py-3 text-xs font-medium text-zinc-300">
                    {item.type.replaceAll('_', ' ')}
                  </td>
                  <td className="px-5 py-3">
                    <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${CHANNEL_BADGE[item.channel] ?? 'text-zinc-400 bg-zinc-800'}`}>
                      {item.channel}
                    </span>
                  </td>
                  <td className="px-5 py-3 max-w-[220px]">
                    <p className="truncate text-sm text-zinc-200">{item.title}</p>
                    <p className="truncate text-xs text-zinc-500">{item.body}</p>
                  </td>
                  <td className="px-5 py-3">
                    <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${STATUS_BADGE[item.status] ?? 'text-zinc-400 bg-zinc-800'}`}>
                      {item.status}
                    </span>
                  </td>
                  <td className="whitespace-nowrap px-5 py-3 text-xs text-zinc-500">
                    {item.sentAt ? new Date(item.sentAt).toLocaleString() : '—'}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between border-t border-zinc-800 px-5 py-3">
            <span className="text-xs text-zinc-500">
              Page {page} of {totalPages} — {result?.total.toLocaleString()} records
            </span>
            <div className="flex items-center gap-2">
              <button
                disabled={page <= 1}
                onClick={() => goToPage(page - 1)}
                className="rounded-lg border border-zinc-700 bg-zinc-800 px-3 py-1.5 text-xs text-zinc-300 transition-colors hover:bg-zinc-700 disabled:cursor-not-allowed disabled:opacity-40"
              >
                Previous
              </button>
              <button
                disabled={page >= totalPages}
                onClick={() => goToPage(page + 1)}
                className="rounded-lg border border-zinc-700 bg-zinc-800 px-3 py-1.5 text-xs text-zinc-300 transition-colors hover:bg-zinc-700 disabled:cursor-not-allowed disabled:opacity-40"
              >
                Next
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
