// src/components/navbar/NotificationsMenu.jsx
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { LuBell } from "react-icons/lu";
import { TbCheck, TbClock, TbRefresh, TbSearch, TbX } from "react-icons/tb";
import ActionMenuPortal from "./ActionMenuPortal";
import { cn, fmtDateTime, normalizeArray } from "../../utils/navbar";

export default function NotificationsMenu({
  onOpen, // () => void (برای بستن منوی دیگر)
  navigate,
  Axiosinstance,
  toastError,
  successToast,
}) {
  const [menu, setMenu] = useState({ open: false, rect: null });

  const close = () => setMenu({ open: false, rect: null });

  const toggle = (e) => {
    e.preventDefault();
    e.stopPropagation();
    onOpen?.(); // مثلا account بسته شود
    const rect = e.currentTarget.getBoundingClientRect();

    setMenu((p) => {
      const nextOpen = !(p.open && p.rect);
      return { open: nextOpen, rect };
    });
  };

  // notifications
  const [notifs, setNotifs] = useState([]);
  const [notifLoading, setNotifLoading] = useState(false);
  const [readingId, setReadingId] = useState(null);

  const unreadCount = useMemo(() => (notifs || []).filter((n) => !n?.is_read).length, [notifs]);
  const topNotifs = useMemo(() => (notifs || []).slice(0, 6), [notifs]);

  const fetchNotifs = useCallback(
    async ({ silent = false } = {}) => {
      if (!silent) setNotifLoading(true);

      try {
        const res = await Axiosinstance.get("accounts/notifications/");
        const arr = normalizeArray(res?.data);

        arr.sort((a, b) => {
          const ta = a?.created_at ? new Date(a.created_at).getTime() : 0;
          const tb = b?.created_at ? new Date(b.created_at).getTime() : 0;
          return tb - ta;
        });

        setNotifs(arr);
      } catch (e) {
        const msg = e?.response?.data?.detail || e?.response?.data?.message || e?.message || "خطا در دریافت نوتیفیکیشن‌ها";

        if (!silent) toastError(msg, { title: "نوتیفیکیشن" });
      } finally {
        if (!silent) setNotifLoading(false);
      }
    },
    [Axiosinstance, toastError]
  );

  const markRead = useCallback(
    async (id) => {
      if (!id) return;

      setNotifs((prev) => (prev || []).map((n) => (String(n?.id) === String(id) ? { ...n, is_read: true } : n)));

      setReadingId(String(id));
      try {
        await Axiosinstance.post(`accounts/notifications/${id}/read/`);
        await fetchNotifs({ silent: true });
        successToast("نوتیفیکیشن خوانده شد.", { title: "موفق" });
      } catch (e) {
        setNotifs((prev) => (prev || []).map((n) => (String(n?.id) === String(id) ? { ...n, is_read: false } : n)));
        toastError(e?.response?.data?.detail || e?.response?.data?.message || e?.message || "خطا در خوانده‌کردن نوتیفیکیشن", { title: "خطا" });
      } finally {
        setReadingId(null);
      }
    },
    [Axiosinstance, fetchNotifs, successToast, toastError]
  );

  // ✅ fetch اولیه + poll برای badge
  useEffect(() => {
    fetchNotifs({ silent: true });

    const interval = setInterval(() => {
      fetchNotifs({ silent: true });
    }, 20000);

    return () => clearInterval(interval);
  }, [fetchNotifs]);

  // وقتی منو باز شد => refresh با loading
  useEffect(() => {
    if (menu.open) fetchNotifs({ silent: false });
  }, [menu.open, fetchNotifs]);

  return (
    <>
      <button
        className="flex text-[#43BEFF] dark:text-white items-center relative"
        type="button"
        onPointerDown={(e) => e.stopPropagation()}
        onClick={toggle}
        aria-haspopup="menu"
        aria-expanded={menu.open}
        aria-label="نوتیفیکیشن‌ها"
      >
        {unreadCount > 0 && (
          <span className="absolute -top-2 -left-2 inline-flex items-center justify-center min-w-5 h-5 px-1 pt-1 rounded-full bg-[#43BEFF] dark:bg-white dark:text-black text-white text-[11px]">
            {unreadCount > 99 ? "99+" : unreadCount}
          </span>
        )}

        {unreadCount > 0 && (
          <span className="relative flex size-2 -mt-7 -ml-2">
            <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-[#43BEFF] dark:bg-white opacity-75"></span>
            <span className="relative inline-flex size-2 rounded-full bg-[#43BEFF] dark:bg-white"></span>
          </span>
        )}

        <LuBell className="h-6 w-6" />
      </button>

      <ActionMenuPortal open={menu.open} rect={menu.rect} onClose={close} width={360} offset={10}>
        <div className="overflow-hidden rounded-2xl dark:text-white max-w-[100vw]">
          {/* header */}
          <div className="p-3 border-b border-black/10 dark:border-white/10 bg-white/60 dark:bg-white/5">
            <div className="flex items-center justify-between">
              <div className="text-sm font-bold dark:text-white text-black">نوتیفیکیشن‌ها</div>

              <button
                type="button"
                onClick={() => fetchNotifs({ silent: false })}
                className="text-xs px-3 py-1.5 rounded-full bg-[#A1E3F980] dark:bg-[#A1E3F919] border border-black/10 dark:border-white/10 hover:bg-[#43BEFF40] dark:hover:bg-[#43BEFF40] transition inline-flex items-center gap-2"
                disabled={notifLoading}
              >
                <TbRefresh className={cn("w-4 h-4", notifLoading ? "animate-spin" : "")} />
                بروزرسانی
              </button>
            </div>

            <div className="mt-2 text-xs text-black/60 dark:text-white/70">
              خوانده‌نشده: <b className={unreadCount ? "text-red-600 dark:text-red-300" : ""}>{unreadCount}</b>
            </div>
          </div>

          {/* content */}
          <div className="max-h-[360px] overflow-y-auto">
            {notifLoading && topNotifs.length === 0 && (
              <div className="p-3 space-y-2">
                {[1, 2, 3].map((i) => (
                  <div key={i} className="h-14 rounded-xl bg-black/5 dark:bg-white/10 animate-pulse" />
                ))}
              </div>
            )}

            {!notifLoading && topNotifs.length === 0 && <div className="py-10 text-center text-sm text-black/50 dark:text-white/60">نوتیفیکیشنی ندارید.</div>}

            {topNotifs.map((n) => {
              const isRead = !!n?.is_read;
              const busy = String(readingId) === String(n?.id);

              return (
                <div key={String(n?.id)} className={cn("px-3 py-3 border-b border-black/10 dark:border-white/10", !isRead ? "bg-[#43BEFF10]" : "bg-transparent")}>
                  <div className="flex items-start gap-3">
                    <div className="w-9 h-9 rounded-xl bg-white/70 dark:bg-white/10 border border-black/10 dark:border-white/10 flex items-center justify-center shrink-0">
                      {isRead ? <TbCheck className="h-5 w-5 text-white bg-green-600 p-1 rounded-full" /> : <TbX className="h-5 w-5 text-white bg-[#001f3f] p-1 rounded-full" />}
                    </div>

                    <div className="flex-1 min-w-0">
                      <div className="flex items-start justify-between gap-2">
                        <div className="min-w-0">
                          <div className="text-sm font-extrabold dark:text-white text-black truncate">{n?.title || "بدون عنوان"}</div>
                          <div className="mt-1 text-xs text-black/60 dark:text-white/70 leading-5 whitespace-pre-line line-clamp-2">{n?.message || "-"}</div>
                        </div>

                        <div className="shrink-0 text-[11px] text-black/50 dark:text-white/60 inline-flex items-center gap-1">
                          <TbClock className="w-4 h-4" />
                          {fmtDateTime(n?.created_at)}
                        </div>
                      </div>

                      {!isRead && (
                        <div className="mt-2 flex justify-end">
                          <button
                            type="button"
                            onClick={() => markRead(n?.id)}
                            disabled={busy}
                            className="text-[11px] px-3 py-1.5 rounded-full bg-[#43BEFF] hover:bg-[#34b6ff] text-white transition disabled:opacity-60"
                          >
                            {busy ? "..." : "خوانده شد"}
                          </button>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>

          {/* footer */}
          <div className="p-3 flex items-center justify-between gap-2 bg-white/60 dark:bg-white/5">
            <button
              type="button"
              onClick={() => {
                navigate("/mynotification");
                close();
              }}
              className="text-xs px-3 py-2 rounded-xl bg-[#A1E3F980] dark:bg-[#A1E3F919] border border-black/10 dark:border-white/10 hover:bg-[#43BEFF40] dark:hover:bg-[#43BEFF40] transition inline-flex items-center gap-2"
            >
              <TbSearch className="w-4 h-4" />
              مشاهده همه
            </button>

            <button type="button" onClick={close} className="text-xs px-3 py-2 rounded-xl border border-black/10 dark:border-white/10 hover:bg-black/5 dark:hover:bg-white/10 transition">
              بستن
            </button>
          </div>
        </div>
      </ActionMenuPortal>
    </>
  );
}
