/**
 * Notification Bell Component
 * Displays notification dropdown with unread count badge
 */

"use client";

import { useState, useRef, useEffect } from "react";
import type { Lang } from "@/lib/config";
import { dashboardEn } from "@/lib/config/translations/modules/dashboard.en";
import { dashboardAr } from "@/lib/config/translations/modules/dashboard.ar";

interface Notification {
  id: string;
  type: string;
  title: string;
  message: string;
  actionUrl?: string;
  isRead: boolean;
  createdAt: string;
}

interface NotificationBellProps {
  lang: Lang;
  notifications: Notification[];
  onMarkAllRead: () => void;
}

export default function NotificationBell({
  lang,
  notifications,
  onMarkAllRead,
}: NotificationBellProps) {
  const isAr = lang === "ar";
  const dt = isAr ? dashboardAr : dashboardEn;
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  const unreadCount = notifications.filter((n) => !n.isRead).length;

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener("mousedown", handleClickOutside);
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isOpen]);

  const getNotificationIcon = (type: string) => {
    switch (type) {
      case "new_booking":
        return "📅";
      case "deposit_received":
        return "💰";
      case "new_conversation":
        return "💬";
      case "booking_reminder":
        return "⏰";
      case "system_alert":
        return "🔔";
      case "integration_error":
        return "⚠️";
      default:
        return "📌";
    }
  };

  const formatTime = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffMinutes = Math.floor((now.getTime() - date.getTime()) / 60000);

    if (diffMinutes < 1) return dt.justNow;
    if (diffMinutes < 60) return `${diffMinutes} ${dt.minutesAgo}`;
    if (diffMinutes < 1440)
      return `${Math.floor(diffMinutes / 60)} ${dt.hoursAgo}`;
    return date.toLocaleDateString(isAr ? "ar-SA" : "en-US", {
      month: "short",
      day: "numeric",
    });
  };

  return (
    <div className="relative" ref={dropdownRef}>
      {/* Bell Button */}
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="relative rounded-lg border border-slate-200 bg-white p-2 text-slate-600 transition-all hover:border-brand-green hover:text-brand-green"
      >
        <svg
          className="h-5 w-5"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"
          />
        </svg>

        {/* Unread Badge */}
        {unreadCount > 0 && (
          <span className="absolute -right-1 -top-1 flex h-5 w-5 items-center justify-center rounded-full bg-rose-500 text-xs font-bold text-white">
            {unreadCount > 9 ? "9+" : unreadCount}
          </span>
        )}
      </button>

      {/* Dropdown */}
      {isOpen && (
        <div
          className={`absolute ${isAr ? "left-0" : "right-0"} mt-2 w-80 sm:w-96 rounded-xl border border-slate-200 bg-white shadow-xl`}
        >
          {/* Header */}
          <div className="flex items-center justify-between border-b border-slate-100 p-4">
            <h3 className="text-sm font-semibold text-slate-900">
              {dt.notifications}
            </h3>
            {unreadCount > 0 && (
              <button
                onClick={onMarkAllRead}
                className="text-xs text-brand-green hover:underline"
              >
                {dt.markAllAsRead}
              </button>
            )}
          </div>

          {/* Notifications List */}
          <div className="max-h-96 overflow-y-auto">
            {notifications.length === 0 ? (
              <div className="flex flex-col items-center justify-center p-8 text-center">
                <div className="text-4xl opacity-20">🔔</div>
                <p className="mt-2 text-sm text-slate-500">
                  {dt.noNotifications}
                </p>
                <p className="text-xs text-slate-400">
                  {dt.noNotificationsDesc}
                </p>
              </div>
            ) : (
              notifications.map((notif) => (
                <div
                  key={notif.id}
                  className={`border-b border-slate-50 p-4 transition-colors hover:bg-slate-50 ${
                    !notif.isRead ? "bg-emerald-50/30" : ""
                  }`}
                >
                  <div className="flex items-start gap-3">
                    <span className="text-2xl">
                      {getNotificationIcon(notif.type)}
                    </span>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-start justify-between gap-2">
                        <p
                          className={`text-sm ${!notif.isRead ? "font-semibold" : "font-medium"} text-slate-900`}
                        >
                          {notif.title}
                        </p>
                        {!notif.isRead && (
                          <span className="h-2 w-2 flex-shrink-0 rounded-full bg-brand-green"></span>
                        )}
                      </div>
                      <p className="mt-0.5 text-xs text-slate-600">
                        {notif.message}
                      </p>
                      <p className="mt-1 text-xs text-slate-400">
                        {formatTime(notif.createdAt)}
                      </p>
                    </div>
                  </div>
                </div>
              ))
            )}
          </div>

          {/* Footer */}
          {notifications.length > 0 && (
            <div className="border-t border-slate-100 p-3 text-center">
              <button className="text-xs font-medium text-brand-green hover:underline">
                {isAr ? "عرض جميع الإشعارات" : "View all notifications"}
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
