// frontend/src/lib/hooks/useNotificationSocket.ts

"use client";

import { useEffect, useRef, useState, useCallback } from "react";
import { io, Socket } from "socket.io-client";
import toast from "react-hot-toast";

const WS_URL =
  process.env.NEXT_PUBLIC_WS_URL ||
  process.env.NEXT_PUBLIC_API_URL?.replace(/\/api\/?$/, "") ||
  "http://localhost:3007";

export interface InquiryNotification {
  dbId: number;
  type: string;
  inquiry_id: number;
  inquiry_ref: string;
  company_name: string;
  message: string;
  old_status: string;
  new_status: string;
  timestamp: string;
  pdf_url?: string;
  docx_url?: string;
}

export function useNotificationSocket() {
  const socketRef = useRef<Socket | null>(null);
  const [connected, setConnected] = useState(false);
  const [unreadCount, setUnreadCount] = useState(0);
  const [latestNotification, setLatestNotification] =
    useState<InquiryNotification | null>(null);

  // Get JWT token from storage
  const getToken = () =>
    localStorage.getItem("access_token") ||
    localStorage.getItem("token") ||
    sessionStorage.getItem("access_token");

  useEffect(() => {
    const token = getToken();
    if (!token) {
      console.warn("[WS] No token — skipping WebSocket connection");
      return;
    }

    // Connect to WebSocket
    const socket = io(`${WS_URL}/inquiry-notifications`, {
      auth: { token },
      transports: ["websocket", "polling"],
      reconnection: true,
      reconnectionAttempts: 10,
      reconnectionDelay: 2000,
    });

    socketRef.current = socket;

    // ── Connection events ───────────────────────────────────────
    socket.on("connect", () => {
      console.log("[WS] ✅ Connected:", socket.id);
      setConnected(true);
    });

    socket.on("disconnect", (reason) => {
      console.log("[WS] ❌ Disconnected:", reason);
      setConnected(false);
    });

    socket.on("connect_error", (err) => {
      console.error("[WS] Connection error:", err.message);
      setConnected(false);
    });

    // ── Welcome message ─────────────────────────────────────────
    socket.on("connected", (data) => {
      console.log("[WS] Welcome:", data);
    });

    // ── Unread count updates ────────────────────────────────────
    socket.on("unread-count", (data: { count: number }) => {
      setUnreadCount(data.count);
    });

    // ── New notification arrives ────────────────────────────────
    socket.on("notification", (data: InquiryNotification) => {
      console.log("[WS] 🔔 New notification:", data);
      setLatestNotification(data);
      setUnreadCount((prev) => prev + 1);

      // Show toast notification
      const typeIcons: Record<string, string> = {
        NEW_INQUIRY: "📋",
        IN_REVIEW: "🔍",
        DRAFT_READY: "📄",
        CHANGES_REQUESTED: "↩",
        CLIENT_CONFIRMED: "✅",
        FINAL_ISSUED: "🏆",
      };
      const icon = typeIcons[data.type] || "🔔";

      toast.success(`${icon} ${data.message}`, {
        duration: 5000,
        position: "top-right",
        style: {
          maxWidth: "420px",
        },
      });

      // Browser notification (if permission granted)
      if (
        typeof window !== "undefined" &&
        "Notification" in window &&
        Notification.permission === "granted"
      ) {
        new Notification(`QRS — ${data.inquiry_ref}`, {
          body: data.message,
          icon: "/favicon.ico",
          tag: `inquiry-${data.inquiry_id}`,
        });
      }
    });

    // Cleanup
    return () => {
      socket.disconnect();
      socketRef.current = null;
    };
  }, []);

  // ── Mark notification as read ─────────────────────────────────
  const markAsRead = useCallback((id: number) => {
    socketRef.current?.emit("mark-read", { id });
  }, []);

  // ── Mark all as read ──────────────────────────────────────────
  const markAllAsRead = useCallback(() => {
    socketRef.current?.emit("mark-all-read");
    setUnreadCount(0);
  }, []);

  // ── Refresh unread count ──────────────────────────────────────
  const refreshUnreadCount = useCallback(() => {
    socketRef.current?.emit("get-unread-count");
  }, []);

  // ── Request browser notification permission ───────────────────
  const requestNotificationPermission = useCallback(async () => {
    if (typeof window === "undefined" || !("Notification" in window)) return;
    if (Notification.permission === "default") {
      const result = await Notification.requestPermission();
      console.log("[WS] Notification permission:", result);
    }
  }, []);

  return {
    connected,
    unreadCount,
    latestNotification,
    markAsRead,
    markAllAsRead,
    refreshUnreadCount,
    requestNotificationPermission,
  };
}