"use client"

import { useState, useEffect, useRef } from "react"
import { Bell, X, CheckCheck, AlertCircle, CreditCard, FileText, Wrench, Info } from "lucide-react"
import { formatDate } from "@/lib/utils"

interface Notification {
  id: string
  type: string
  subject: string
  read: boolean
  sent_at: string
  metadata?: { body?: string } & Record<string, unknown>
}

const typeIcon: Record<string, React.ElementType> = {
  rent_due:          CreditCard,
  rent_overdue:      AlertCircle,
  lease_expiry:      FileText,
  maintenance_update: Wrench,
  general:           Info,
}

const typeColor: Record<string, string> = {
  rent_due:           "text-amber-400 bg-amber-500/10",
  rent_overdue:       "text-red-400 bg-red-500/10",
  lease_expiry:       "text-orange-400 bg-orange-500/10",
  maintenance_update: "text-blue-400 bg-blue-500/10",
  general:            "text-white/40 bg-white/5",
}

export function NotificationsBell() {
  const [open, setOpen]     = useState(false)
  const [notifs, setNotifs] = useState<Notification[]>([])
  const [loading, setLoading] = useState(false)
  const ref = useRef<HTMLDivElement>(null)

  const unread = notifs.filter(n => !n.read).length

  async function load() {
    setLoading(true)
    try {
      const res = await fetch("/api/notifications")
      if (res.ok) setNotifs(await res.json())
    } finally {
      setLoading(false)
    }
  }

  async function markAllRead() {
    const prev = [...notifs]
    setNotifs(n => n.map(x => ({ ...x, read: true })))
    try {
      const res = await fetch("/api/notifications/read", { method: "PATCH" })
      if (!res.ok) throw new Error()
    } catch {
      setNotifs(prev) // rollback on failure
    }
  }

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

  useEffect(() => {
    function onOutside(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false)
    }
    document.addEventListener("mousedown", onOutside)
    return () => document.removeEventListener("mousedown", onOutside)
  }, [])

  return (
    <div ref={ref} className="relative">
      <button
        onClick={() => setOpen(v => !v)}
        className="relative flex h-9 w-9 items-center justify-center rounded-xl border border-white/[0.06] bg-white/[0.03] text-white/40 hover:text-white hover:bg-white/[0.06] transition-all"
      >
        <Bell className="h-4 w-4" />
        {unread > 0 && (
          <span className="absolute -top-1 -right-1 flex h-4 w-4 items-center justify-center rounded-full bg-red-500 text-[9px] font-bold text-white">
            {unread > 9 ? "9+" : unread}
          </span>
        )}
      </button>

      {open && (
        <div className="absolute right-0 top-11 z-50 w-80 sm:w-96 rounded-2xl border border-white/[0.08] bg-[#111118] shadow-2xl shadow-black/60 overflow-hidden">
          {/* Header */}
          <div className="flex items-center justify-between px-4 py-3 border-b border-white/[0.06]">
            <div className="flex items-center gap-2">
              <Bell className="h-4 w-4 text-white/40" />
              <span className="text-sm font-semibold text-white">Notifications</span>
              {unread > 0 && (
                <span className="rounded-full bg-red-500/20 px-1.5 py-0.5 text-[10px] font-bold text-red-400">{unread}</span>
              )}
            </div>
            <div className="flex items-center gap-2">
              {unread > 0 && (
                <button onClick={markAllRead} className="flex items-center gap-1 text-[10px] text-indigo-400 hover:text-indigo-300 transition">
                  <CheckCheck className="h-3 w-3" /> Mark all read
                </button>
              )}
              <button onClick={() => setOpen(false)} className="p-1 text-white/30 hover:text-white transition">
                <X className="h-3.5 w-3.5" />
              </button>
            </div>
          </div>

          {/* List */}
          <div className="max-h-[400px] overflow-y-auto">
            {loading ? (
              <div className="py-10 text-center text-sm text-white/30">Loading…</div>
            ) : notifs.length === 0 ? (
              <div className="py-12 text-center">
                <Bell className="h-8 w-8 text-white/10 mx-auto mb-3" />
                <p className="text-sm text-white/30">No notifications yet</p>
              </div>
            ) : (
              <div className="divide-y divide-white/[0.04]">
                {notifs.map((n) => {
                  const Icon = typeIcon[n.type] ?? Info
                  const color = typeColor[n.type] ?? typeColor.general
                  return (
                    <div key={n.id} className={`flex gap-3 px-4 py-3 transition ${!n.read ? "bg-indigo-500/[0.04]" : ""}`}>
                      <div className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-xl ${color}`}>
                        <Icon className="h-3.5 w-3.5" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className={`text-sm font-medium leading-tight ${n.read ? "text-white/60" : "text-white"}`}>{n.subject}</p>
                        {typeof n.metadata?.body === "string" && n.metadata.body && (
                          <p className="text-xs text-white/35 mt-0.5 line-clamp-2">{n.metadata.body}</p>
                        )}
                        <p className="text-[10px] text-white/20 mt-1">{formatDate(n.sent_at)}</p>
                      </div>
                      {!n.read && <div className="h-2 w-2 rounded-full bg-indigo-500 shrink-0 mt-1.5" />}
                    </div>
                  )
                })}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  )
}
