"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import toast from "react-hot-toast";

import DashboardSidebar from "@/app/components/astrologer/DashboardSidebar";
import {
  NotificationItem,
  clearNotifications,
  deleteNotification,
  deleteNotifications,
  getNotifications,
  markNotificationsRead,
  matchLiveConsultationRequest,
} from "@/app/lib/notifications";
import {
  ConsultationRequest,
  acceptConsultation,
  getConsultationRequests,
  rejectConsultation,
} from "@/app/lib/astrologer";

// How often the still-open ring queue is re-checked so a notification's
// Accept/Reject card stays accurate (countdown, and it disappearing the
// moment the request is answered/expired elsewhere) — same cadence as
// the Orders hub's own poll.
const REQUEST_POLL_MS = 4000;

function initials(name?: string) {
  return (
    (name || "?")
      .trim()
      .split(/\s+/)
      .slice(0, 2)
      .map((part) => part.charAt(0).toUpperCase())
      .join("") || "?"
  );
}

export default function AstrologerNotificationsPage() {
  const router = useRouter();

  const [items, setItems] = useState<NotificationItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set());

  // A CONSULTATION_REQUEST notification is only actionable while the
  // underlying request is still actually ringing — rather than guess at
  // an unconfirmed numeric notification_type code, cross-reference each
  // notification's chat_request_id/call_request_id against the real,
  // live ring queue (the same endpoint the Orders hub polls). If it's
  // not in there, the request has already been accepted/rejected/expired
  // and the notification renders as a plain read-only row instead.
  const [openRequests, setOpenRequests] = useState<Map<number, ConsultationRequest>>(
    new Map(),
  );
  const [requestSeconds, setRequestSeconds] = useState<Record<number, number>>({});
  const [actingId, setActingId] = useState<number | null>(null);
  const tokenRef = useRef<string | null>(null);

  const load = useCallback(async (targetPage: number) => {
    const token = localStorage.getItem("astrologerToken");

    if (!token) {
      router.replace("/astrologer/signin");
      return;
    }

    setLoading(true);

    const result = await getNotifications("astrologer", token, {
      page: targetPage,
      limit: 15,
    });

    setItems(result.list);
    setTotalPages(result.pagination?.totalPages ?? 1);
    setSelectedIds(new Set());
    setLoading(false);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

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

  useEffect(() => {
    const token = localStorage.getItem("astrologerToken");
    if (!token) return;

    tokenRef.current = token;
    let cancelled = false;

    const poll = async () => {
      let response;

      try {
        response = await getConsultationRequests(token);
      } catch (error) {
        console.error("Ring queue poll (notifications page) failed:", error);
        return;
      }

      if (cancelled || !response?.success) return;

      const nextItems: ConsultationRequest[] = response.data?.items ?? response.items ?? [];

      setOpenRequests(new Map(nextItems.map((r) => [r.consultation_id, r])));

      setRequestSeconds((previous) => {
        const next = { ...previous };
        nextItems.forEach((r) => {
          if (r.seconds_to_expiry != null) next[r.consultation_id] = Number(r.seconds_to_expiry);
        });
        return next;
      });
    };

    poll();
    const interval = setInterval(poll, REQUEST_POLL_MS);

    return () => {
      cancelled = true;
      clearInterval(interval);
    };
  }, []);

  // Local 1s ticker — never recompute a ring countdown from a raw
  // timestamp on the device clock (confirmed elsewhere in this app that
  // it drifts badly); count down the server's own seconds_to_expiry.
  useEffect(() => {
    const interval = setInterval(() => {
      setRequestSeconds((previous) => {
        const next: Record<number, number> = {};
        Object.entries(previous).forEach(([id, seconds]) => {
          next[Number(id)] = Math.max(0, seconds - 1);
        });
        return next;
      });
    }, 1000);

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

  // Fresh per render — stops the same still-open request being attached
  // to more than one historical notification about the same customer.
  const claimedRequestIds = new Set<number>();

  const getLiveRequest = (item: NotificationItem): ConsultationRequest | undefined =>
    matchLiveConsultationRequest(item, openRequests, claimedRequestIds);

  const handleAcceptFromNotification = async (
    item: NotificationItem,
    request: ConsultationRequest,
  ) => {
    const token = tokenRef.current;
    if (!token) return;

    try {
      setActingId(request.consultation_id);
      const response = await acceptConsultation(request.consultation_id, token, request);

      if (!response.success) {
        const silent = [
          "this consultation is no longer available",
          "you are already in a consultation",
          "the customer no longer has sufficient balance",
        ];

        if (!silent.some((m) => (response.message || "").toLowerCase().includes(m))) {
          toast.error(response.message || "Unable to accept this request.");
        }

        setOpenRequests((prev) => {
          const next = new Map(prev);
          next.delete(request.consultation_id);
          return next;
        });
        return;
      }

      setItems((prev) => prev.map((n) => (n.id === item.id ? { ...n, is_read: true } : n)));
      router.push(`/astrologer/consultation/${request.consultation_id}`);
    } finally {
      setActingId(null);
    }
  };

  const handleRejectFromNotification = async (
    item: NotificationItem,
    request: ConsultationRequest,
  ) => {
    const token = tokenRef.current;
    if (!token) return;

    try {
      setActingId(request.consultation_id);
      await rejectConsultation(request.consultation_id, "Not available right now", token);

      setOpenRequests((prev) => {
        const next = new Map(prev);
        next.delete(request.consultation_id);
        return next;
      });

      setItems((prev) => prev.map((n) => (n.id === item.id ? { ...n, is_read: true } : n)));
      await markNotificationsRead("astrologer", token, { ids: [item.id] });
    } finally {
      setActingId(null);
    }
  };

  const openItem = async (item: NotificationItem) => {
    if (item.is_read) return;

    const token = localStorage.getItem("astrologerToken");
    if (!token) return;

    setItems((prev) =>
      prev.map((n) => (n.id === item.id ? { ...n, is_read: true } : n)),
    );

    await markNotificationsRead("astrologer", token, { ids: [item.id] });
  };

  const markAllRead = async () => {
    const token = localStorage.getItem("astrologerToken");
    if (!token) return;

    setItems((prev) => prev.map((n) => ({ ...n, is_read: true })));
    await markNotificationsRead("astrologer", token, { all: true });
  };

  const removeItem = async (id: number) => {
    const token = localStorage.getItem("astrologerToken");
    if (!token) return;

    setItems((prev) => prev.filter((n) => n.id !== id));
    await deleteNotification("astrologer", token, id);
  };

  const clearAll = async () => {
    const token = localStorage.getItem("astrologerToken");
    if (!token) return;

    setItems([]);
    setSelectedIds(new Set());
    await clearNotifications("astrologer", token);
  };

  const toggleSelected = (id: number) => {
    setSelectedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const toggleSelectAll = () => {
    setSelectedIds((prev) =>
      prev.size === items.length ? new Set() : new Set(items.map((n) => n.id)),
    );
  };

  const deleteSelected = async () => {
    const token = localStorage.getItem("astrologerToken");
    if (!token || selectedIds.size === 0) return;

    const ids = Array.from(selectedIds);
    setItems((prev) => prev.filter((n) => !selectedIds.has(n.id)));
    setSelectedIds(new Set());
    await deleteNotifications("astrologer", token, ids);
  };

  return (
    <div className="astrologer-dashboard-shell">
      <DashboardSidebar active="Notifications" />

      <main className="astrologer-dashboard-main">
        <div className="astrologer-dashboard-topbar d-flex flex-wrap align-items-center justify-content-between gap-3">
          <div className="astrologer-dashboard-name">Notifications</div>

          {items.length > 0 && (
            <div className="d-flex gap-2">
              <button
                type="button"
                className="btn btn-outline-light btn-sm rounded-pill px-3"
                onClick={markAllRead}
              >
                Mark all as read
              </button>
              <button
                type="button"
                className="btn btn-outline-danger btn-sm rounded-pill px-3"
                onClick={clearAll}
              >
                Clear all
              </button>
            </div>
          )}
        </div>

        <div className="astrologer-panel card-bg-primary">
          {items.length > 0 && (
            <div className="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-3">
              <label
                className="d-flex align-items-center gap-2 terms-text-color small mb-0"
                style={{ cursor: "pointer" }}
              >
                <input
                  type="checkbox"
                  checked={selectedIds.size === items.length}
                  onChange={toggleSelectAll}
                />
                Select all on this page
              </label>

              {selectedIds.size > 0 && (
                <button
                  type="button"
                  className="btn btn-danger btn-sm rounded-pill px-3"
                  onClick={deleteSelected}
                >
                  Delete selected ({selectedIds.size})
                </button>
              )}
            </div>
          )}

          {loading ? (
            <p className="mb-0">Loading...</p>
          ) : items.length === 0 ? (
            <p className="astrologer-empty-hint mb-0">No notifications yet.</p>
          ) : (
            <div className="d-flex flex-column gap-2">
              {items.map((item) => {
                const liveRequest = getLiveRequest(item);

                // A request notification whose consultation isn't in the
                // live ring queue anymore has already been accepted,
                // rejected or has expired elsewhere — render it as a
                // plain read-only row rather than offering actions on a
                // request that no longer exists.
                if (liveRequest) {
                  const seconds =
                    requestSeconds[liveRequest.consultation_id] ??
                    liveRequest.seconds_to_expiry ??
                    0;
                  const displayName =
                    liveRequest.consultee_name || liveRequest.user_name || "User";
                  const acting = actingId === liveRequest.consultation_id;

                  return (
                    <div key={item.id} className="waiting-request-card">
                      <div className="d-flex align-items-start gap-2 mb-2">
                        <input
                          type="checkbox"
                          className="mt-1"
                          checked={selectedIds.has(item.id)}
                          onClick={(e) => e.stopPropagation()}
                          onChange={() => toggleSelected(item.id)}
                        />
                        <div className="flex-fill">
                          <div className="fw-bold small" style={{ color: "#f5c400" }}>
                            {item.title}
                          </div>
                          <div className="terms-text-color small">{item.time_ago}</div>
                        </div>
                      </div>

                      <div className="waiting-request-top">
                        <div className="waiting-user-avatar">{initials(displayName)}</div>

                        <div className="waiting-request-info">
                          <div className="waiting-user-name">{displayName}</div>
                          <div className="waiting-request-topic">
                            <span>{liveRequest.medium === "CHAT" ? "💬" : "📞"}</span>
                            {liveRequest.medium === "CHAT"
                              ? "Chat consultation"
                              : "Call consultation"}
                          </div>
                          {liveRequest.consultee_birth_date && (
                            <div className="waiting-request-time">
                              <span>🎂</span>
                              {liveRequest.consultee_birth_date} {liveRequest.consultee_birth_time}
                              {liveRequest.consultee_birth_place
                                ? ` · ${liveRequest.consultee_birth_place}`
                                : ""}
                            </div>
                          )}
                        </div>

                        <div className={`waiting-expiry ${seconds <= 10 ? "danger" : ""}`}>
                          {seconds}s
                        </div>
                      </div>

                      <div className="waiting-request-meta">
                        {liveRequest.is_free_chat ? (
                          <span className="waiting-free-badge">
                            FREE {liveRequest.free_minutes ?? 0} min · you earn ₹
                            {liveRequest.estimated_earning ?? 0}
                          </span>
                        ) : (
                          <span>
                            ₹{liveRequest.rate_per_minute ?? 0}/min · you earn ₹
                            {liveRequest.estimated_earning ?? 0}
                          </span>
                        )}
                      </div>

                      <div className="waiting-request-actions">
                        <button
                          type="button"
                          className="waiting-decline-btn"
                          disabled={acting}
                          onClick={() => handleRejectFromNotification(item, liveRequest)}
                        >
                          {acting ? "..." : "Reject"}
                        </button>

                        <button
                          type="button"
                          className="waiting-accept-btn"
                          disabled={acting}
                          onClick={() => handleAcceptFromNotification(item, liveRequest)}
                        >
                          <span>{liveRequest.medium === "CHAT" ? "💬" : "📞"}</span>
                          {acting ? "Accepting..." : "Accept"}
                        </button>
                      </div>
                    </div>
                  );
                }

                return (
                  <div
                    key={item.id}
                    className="d-flex justify-content-between align-items-start gap-3 p-3 rounded-3"
                    style={{
                      background: item.is_read ? "#00000022" : "#FFC10722",
                      cursor: item.is_read ? "default" : "pointer",
                    }}
                    onClick={() => openItem(item)}
                  >
                    <div className="d-flex align-items-start gap-3">
                      <input
                        type="checkbox"
                        className="mt-1"
                        checked={selectedIds.has(item.id)}
                        onClick={(e) => e.stopPropagation()}
                        onChange={() => toggleSelected(item.id)}
                      />

                      <div>
                        <div className="fw-bold mb-1 d-flex align-items-center gap-2">
                          {!item.is_read && (
                            <span
                              style={{
                                width: 8,
                                height: 8,
                                borderRadius: "50%",
                                background: "#FFC107",
                                display: "inline-block",
                              }}
                            />
                          )}
                          {item.title}
                        </div>
                        <div className="terms-text-color small">{item.description}</div>
                      </div>
                    </div>

                    <div className="d-flex flex-column align-items-end gap-2">
                      <small className="terms-text-color">{item.time_ago}</small>

                      <button
                        type="button"
                        className="notification-remove-btn"
                        aria-label="Remove notification"
                        title="Remove"
                        onClick={(e) => {
                          e.stopPropagation();
                          removeItem(item.id);
                        }}
                      >
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m3 0-1 14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2L4 6h16ZM10 11v6M14 11v6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                        </svg>
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          )}

          {totalPages > 1 && (
            <div className="d-flex justify-content-center gap-2 mt-4">
              <button
                type="button"
                className="btn btn-outline-light btn-sm"
                disabled={page <= 1}
                onClick={() => setPage((p) => Math.max(1, p - 1))}
              >
                Previous
              </button>
              <span className="align-self-center">
                Page {page} of {totalPages}
              </span>
              <button
                type="button"
                className="btn btn-outline-light btn-sm"
                disabled={page >= totalPages}
                onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
              >
                Next
              </button>
            </div>
          )}
        </div>
      </main>
    </div>
  );
}
