"use client";

import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import { Bell } from "lucide-react";
import { useTranslations } from "next-intl";
import { useLocale } from "next-intl";
import { usePathname, useRouter } from "next/navigation";
import { useSession } from "@/auth/session-provider";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import {
  fetchNotifications,
  markNotificationsAsRead,
  deleteNotifications,
} from "@/lib/api";
import { buildNotificationHref } from "@/lib/notificationHref";
import type { Notification } from "@/types/api/notifications.types";
import { onNewNotification } from "@/lib/notificationEvents";

// Format date helper
const formatDate = (dateString: string, lang: string) => {
  const date = new Date(dateString);
  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffMins = Math.floor(diffMs / 60000);
  const diffHours = Math.floor(diffMs / 3600000);
  const diffDays = Math.floor(diffMs / 86400000);

  if (lang === "ar") {
    if (diffMins < 1) return "الآن";
    if (diffMins < 60) return `منذ ${diffMins} دقيقة`;
    if (diffHours < 24) return `منذ ${diffHours} ساعة`;
    if (diffDays < 7) return `منذ ${diffDays} يوم${diffDays > 1 ? "s" : ""}`;
    return date.toLocaleDateString("ar-SA", {
      day: "numeric",
      month: "short",
      year: "numeric",
    });
  } else {
    if (diffMins < 1) return "Just now";
    if (diffMins < 60) return `${diffMins}m ago`;
    if (diffHours < 24) return `${diffHours}h ago`;
    if (diffDays < 7) return `${diffDays}d ago`;
    return date.toLocaleDateString("en-US", {
      day: "numeric",
      month: "short",
      year: "numeric",
    });
  }
};

export default function NotificationDropdown() {
  const t = useTranslations("DASHBOARD.NOTIFICATIONS");
  const lang = useLocale();
  const router = useRouter();
  const pathname = usePathname();
  const requestLang = (() => {
    const seg = String(pathname || "").split("/")[1] || "";
    const v = seg.toLowerCase();
    if (v === "ar" || v.startsWith("ar")) return "ar";
    if (v === "en" || v.startsWith("en")) return "en";
    const fallback = String(lang || "").toLowerCase();
    return fallback.startsWith("ar") ? "ar" : "en";
  })();
  const session = useSession();
  const token = session?.access_token;
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [loading, setLoading] = useState(false);
  console.log(notifications);
  const isAr = requestLang === "ar";

  const unreadCount = notifications.filter((n) => n.read_at === null).length;

  const loadNotifications = useCallback(async () => {
    try {
      if (!token) return;
      setLoading(true);
      const response = await fetchNotifications(10, token, requestLang);
      setNotifications(response.data.data);
    } catch (err) {
      console.error("Failed to load notifications:", err);
    } finally {
      setLoading(false);
    }
  }, [token, requestLang]);

  useEffect(() => {
    if (token) {
      loadNotifications();
    }
    if (!token) {
      setNotifications([]);
    }
  }, [token, requestLang, loadNotifications]);

  // Subscribe to real-time push notification events
  useEffect(() => {
    const unsubscribe = onNewNotification(() => {
      // Refresh notifications from the API when a new push arrives
      loadNotifications();
    });
    return unsubscribe;
  }, [loadNotifications]);

  const handleMarkAsRead = async (notificationIds: string[]) => {
    try {
      await markNotificationsAsRead(notificationIds, token, requestLang);
      setNotifications((prev) =>
        prev.map((n) =>
          notificationIds.includes(n.id)
            ? { ...n, read_at: new Date().toISOString() }
            : n,
        ),
      );
    } catch (err) {
      console.error("Failed to mark as read:", err);
    }
  };

  const handleNotificationClick = async (notification: Notification) => {
    if (notification.read_at === null) {
      await handleMarkAsRead([notification.id]);
    }

    const href = buildNotificationHref(notification, requestLang);
    if (href) router.push(href);
  };

  const getNotificationIcon = (title: string) => {
    const lowerTitle = title.toLowerCase();
    if (lowerTitle.includes("accepted") || lowerTitle.includes("approved")) {
      return "✅";
    } else if (
      lowerTitle.includes("rejected") ||
      lowerTitle.includes("error")
    ) {
      return "❌";
    } else if (lowerTitle.includes("warning") || lowerTitle.includes("soon")) {
      return "⚠️";
    } else {
      return "ℹ️";
    }
  };

  if (!session) {
    return null;
  }

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <button
          type="button"
          aria-label="Notifications"
          className="relative inline-flex items-center justify-center rounded-md p-2 text-gray-600 hover:text-green-700 hover:bg-gray-100 transition-colors"
        >
          <Bell size={20} />
          {unreadCount > 0 && (
            <span className="absolute -top-1 -right-1 min-w-4.5 h-4.5 rounded-full bg-red-500 text-white text-[10px] leading-4.5 text-center px-1">
              {unreadCount > 99 ? "99+" : unreadCount}
            </span>
          )}
        </button>
      </DropdownMenuTrigger>

      <DropdownMenuContent
        className={`w-87.5 max-w-[90vw] ${isAr ? "text-right" : "text-left"}`}
      >
        {loading ? (
          <div
            className={`px-3 py-4 text-sm text-gray-500 ${isAr ? "text-right" : "text-left"}`}
          >
            {t("retry")}
          </div>
        ) : notifications.length === 0 ? (
          <div
            className={`px-3 py-4 text-sm text-gray-500 ${isAr ? "text-right" : "text-left"}`}
          >
            {t("no_notifications")}
          </div>
        ) : (
          <>
            {notifications.slice(0, 5).map((notification) => (
              <DropdownMenuItem
                key={notification.id}
                className={`flex cursor-pointer items-start gap-3 py-3 ${isAr ? "flex-row-reverse" : "flex-row"}`}
                onSelect={() => {
                  void handleNotificationClick(notification);
                }}
              >
                <span className="text-lg shrink-0">
                  {getNotificationIcon(notification.title)}
                </span>
                <div
                  className={`flex-1 min-w-0 ${isAr ? "text-right" : "text-left"}`}
                >
                  <div
                    className={`flex items-start justify-between gap-2 ${isAr ? "flex-row-reverse" : "flex-row"}`}
                  >
                    <div
                      className={`text-sm truncate ${
                        notification.read_at === null
                          ? "text-gray-900 font-semibold"
                          : "text-gray-700"
                      }`}
                    >
                      {notification.title}
                    </div>
                    {notification.read_at === null && (
                      <div className="w-2 h-2 bg-blue-600 rounded-full shrink-0 mt-1" />
                    )}
                  </div>
                  <div
                    className={`text-xs text-gray-500 mt-1 line-clamp-2 ${isAr ? "text-right" : "text-left"}`}
                  >
                    {notification.body}
                  </div>
                  <div
                    dir={isAr ? "ltr" : "rtl"}
                    className={`text-xs text-gray-400 mt-1 ${
                      isAr ? "text-left" : "text-right"
                    }`}
                  >
                    {formatDate(notification.created_at, requestLang)}
                  </div>
                </div>
              </DropdownMenuItem>
            ))}

            <DropdownMenuSeparator />

            <div
              className={`px-2 py-2 flex items-center justify-between ${isAr ? "flex-row-reverse" : "flex-row"}`}
            >
              <span className="text-xs text-gray-500">
                {unreadCount > 0 && `${unreadCount} ${t("unread")}`}
              </span>
              <div
                className={`flex items-center gap-2 ${isAr ? "flex-row-reverse" : "flex-row"}`}
              >
                {unreadCount > 0 && (
                  <button
                    type="button"
                    className="text-xs text-blue-600 hover:text-blue-700"
                    onClick={(e) => {
                      e.preventDefault();
                      handleMarkAsRead(
                        notifications
                          .filter((n) => n.read_at === null)
                          .map((n) => n.id),
                      );
                    }}
                  >
                    {t("mark_all_read")}
                  </button>
                )}

                <Link
                  href={`/${requestLang}/dashboard?tab=notifications`}
                  className="text-xs text-red-600 hover:text-red-700"
                >
                  {t("view_all")}
                </Link>
              </div>
            </div>
          </>
        )}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
