'use client'

import { useState, useEffect, useRef } from 'react'
import { Bell, Check, CheckCheck, Trash2, X, Megaphone, MessageSquare, Home, Star } from 'lucide-react'

type Notification = {
  id: string; title: string; body: string; type: string
  read: boolean; createdAt: string; data?: any
}

const TYPE_ICONS: Record<string, React.ReactNode> = {
  PUSH:      <Megaphone     className="w-4 h-4 text-blue-500"   />,
  MESSAGE:   <MessageSquare className="w-4 h-4 text-green-500" />,
  PROPERTY:  <Home          className="w-4 h-4 text-purple-500" />,
  REVIEW:    <Star          className="w-4 h-4 text-amber-500"  />,
}

function timeAgo(date: string): string {
  const diff = Date.now() - new Date(date).getTime()
  const mins = Math.floor(diff / 60000)
  if (mins < 1)  return 'الآن'
  if (mins < 60) return `منذ ${mins} دقيقة`
  const hrs = Math.floor(mins / 60)
  if (hrs < 24)  return `منذ ${hrs} ساعة`
  return `منذ ${Math.floor(hrs / 24)} يوم`
}

export function NotificationBell({ userId }: { userId?: string }) {
  const [open, setOpen]                 = useState(false)
  const [notifications, setNotifications] = useState<Notification[]>([])
  const [unread, setUnread]             = useState(0)
  const [loading, setLoading]           = useState(false)
  const ref = useRef<HTMLDivElement>(null)

  const DEMO: Notification[] = [
    { id: '1', title: 'رسالة جديدة',       body: 'أحمد العلوي يسأل عن شقة المعاريف',         type: 'MESSAGE',  read: false, createdAt: new Date(Date.now() - 300000).toISOString() },
    { id: '2', title: 'عقار محجوز',     body: 'تم حجز فيلا مراكش من قِبل عميل',           type: 'PROPERTY', read: false, createdAt: new Date(Date.now() - 3600000).toISOString() },
    { id: '3', title: 'تقييم جديد',      body: 'حصل عقارك على تقييم 5 نجوم',               type: 'REVIEW',   read: true,  createdAt: new Date(Date.now() - 86400000).toISOString() },
  ]

  const load = async () => {
    if (!userId) {
      setNotifications(DEMO)
      setUnread(DEMO.filter(n => !n.read).length)
      return
    }
    setLoading(true)
    try {
      const res = await fetch(`/api/notifications?userId=${userId}&limit=15`)
      const data = await res.json()
      setNotifications(data.notifications ?? [])
      setUnread(data.unreadCount ?? 0)
    } catch {}
    finally { setLoading(false) }
  }

  useEffect(() => {
    if (!userId) { load(); return }

    load()

    let interval: ReturnType<typeof setInterval> | null = null

    const startPolling = () => {
      if (interval) return
      interval = setInterval(load, 60000)
    }

    const stopPolling = () => {
      if (interval) { clearInterval(interval); interval = null }
    }

    if (document.visibilityState === 'visible') startPolling()

    const onVisChange = () => {
      if (document.visibilityState === 'visible') startPolling()
      else stopPolling()
    }

    document.addEventListener('visibilitychange', onVisChange)
    return () => { stopPolling(); document.removeEventListener('visibilitychange', onVisChange) }
  }, [userId])

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

  const markAllRead = async () => {
    setNotifications(prev => prev.map(n => ({ ...n, read: true })))
    setUnread(0)
    if (userId) {
      await fetch('/api/notifications', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ userId }) })
    }
  }

  const markOne = async (id: string) => {
    setNotifications(prev => prev.map(n => n.id === id ? { ...n, read: true } : n))
    setUnread(prev => Math.max(prev - 1, 0))
    if (userId) {
      await fetch('/api/notifications', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ userId, notificationId: id }) })
    }
  }

  const remove = async (id: string) => {
    const wasUnread = notifications.find(n => n.id === id)?.read === false
    setNotifications(prev => prev.filter(n => n.id !== id))
    if (wasUnread) setUnread(prev => Math.max(prev - 1, 0))
    if (userId) await fetch(`/api/notifications?id=${id}&userId=${userId}`, { method: 'DELETE' })
  }

  return (
    <div ref={ref} className="relative">
      <button
        onClick={() => { setOpen(!open); if (!open) load() }}
        className="relative p-2 rounded-xl hover:bg-gray-100 transition-colors"
        aria-label="الإشعارات"
      >
        <Bell className="w-5 h-5 text-gray-600" />
        {unread > 0 && (
          <span className="absolute -top-0.5 -right-0.5 w-5 h-5 bg-red-500 text-white text-xs rounded-full flex items-center justify-center font-bold animate-pulse">
            {unread > 9 ? '9+' : unread}
          </span>
        )}
      </button>

      {open && (
        <div className="absolute left-0 top-12 w-80 bg-white border border-gray-100 rounded-2xl shadow-2xl z-50 overflow-hidden" dir="rtl">
          <div className="flex items-center justify-between px-4 py-3 border-b bg-gray-50">
            <h3 className="font-bold text-sm">الإشعارات</h3>
            <div className="flex items-center gap-2">
              {unread > 0 && (
                <button onClick={markAllRead} className="text-xs text-blue-600 hover:text-blue-800 flex items-center gap-1">
                  <CheckCheck className="w-3.5 h-3.5" /> قراءة الكل
                </button>
              )}
              <button onClick={() => setOpen(false)} className="text-gray-400 hover:text-gray-600">
                <X className="w-4 h-4" />
              </button>
            </div>
          </div>

          <div className="max-h-80 overflow-y-auto">
            {loading && notifications.length === 0 ? (
              <div className="p-8 text-center text-gray-400 text-sm">
                <div className="w-6 h-6 border-2 border-blue-400 border-t-transparent rounded-full animate-spin mx-auto mb-2" />
                جاري التحميل...
              </div>
            ) : notifications.length === 0 ? (
              <div className="p-8 text-center text-gray-400">
                <Bell className="w-10 h-10 mx-auto mb-2 opacity-20" />
                <p className="text-sm">لا توجد إشعارات</p>
              </div>
            ) : (
              notifications.map(n => (
                <div key={n.id}
                  className={`flex gap-3 px-4 py-3 border-b border-gray-50 hover:bg-gray-50 transition-colors group ${!n.read ? 'bg-blue-50/40' : ''}`}
                >
                  <div className="mt-0.5 shrink-0 w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center">
                    {TYPE_ICONS[n.type] ?? <Bell className="w-4 h-4 text-gray-400" />}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className={`text-sm ${!n.read ? 'font-semibold text-gray-900' : 'text-gray-700'}`}>{n.title}</p>
                    <p className="text-xs text-gray-500 mt-0.5 line-clamp-2">{n.body}</p>
                    <p className="text-xs text-gray-400 mt-1">{timeAgo(n.createdAt)}</p>
                  </div>
                  <div className="flex flex-col gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
                    {!n.read && (
                      <button onClick={() => markOne(n.id)} className="text-blue-400 hover:text-blue-600" aria-label="تعليم كمقروء">
                        <Check className="w-3.5 h-3.5" />
                      </button>
                    )}
                    <button onClick={() => remove(n.id)} className="text-red-300 hover:text-red-500" aria-label="حذف">
                      <Trash2 className="w-3.5 h-3.5" />
                    </button>
                  </div>
                  {!n.read && <div className="w-2 h-2 bg-blue-500 rounded-full mt-1.5 shrink-0" />}
                </div>
              ))
            )}
          </div>

          {notifications.length > 0 && (
            <div className="px-4 py-2.5 border-t bg-gray-50 text-center">
              <button onClick={() => { setNotifications([]); setUnread(0); setOpen(false) }}
                className="text-xs text-red-400 hover:text-red-600 transition-colors">
                مسح جميع الإشعارات
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  )
}
