/* eslint-disable @typescript-eslint/no-explicit-any */
import PQueue from "p-queue";

let ports: chrome.runtime.Port[] = [];
const queue = new PQueue({ concurrency: 1 });

chrome.runtime.onConnect.addListener((port) => {
  ports.push(port);
  port.onDisconnect.addListener(() => {
    ports = ports.filter((p) => p !== port);
  });
});

// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function handlePublish(data: any, timeoutMs = 5 * 60 * 1000) {
  return new Promise<void>((resolve) => {
    chrome.tabs.create(
      { url: "https://www.facebook.com/marketplace/create/item", active: true },
      (tab) => {
        if (!tab?.id) return resolve();
        const tabId = tab.id;

        let resolved = false;
        const cleanup = () => {
          if (resolved) return;
          resolved = true;
          chrome.runtime.onConnect.removeListener(onConnectListener);
          chrome.tabs.onRemoved.removeListener(onTabClosed);
          clearTimeout(timeoutId);
          resolve();
          ensureMarketplaceSellingTab();
        };

        const onConnectListener = (port: chrome.runtime.Port) => {
          if (port.sender?.tab?.id === tabId) {
            port.postMessage({ type: "publist-event", payload: data });
            chrome.runtime.onConnect.removeListener(onConnectListener);
          }
        };
        chrome.runtime.onConnect.addListener(onConnectListener);

        const onTabClosed = (closedTabId: number) => {
          if (closedTabId === tabId) {
            cleanup();
          }
        };
        chrome.tabs.onRemoved.addListener(onTabClosed);

        // Timeout tùy chỉnh
        const timeoutId = setTimeout(() => {
          console.warn(`Tab ${tabId} timeout (${timeoutMs}ms) - auto resolve`);
          if (tabId) chrome.tabs.remove(tabId);
          cleanup();
        }, timeoutMs);
      }
    );
  });
}

const handleListenPublists = () => {
  const evtSource = new EventSource(
    `${import.meta.env.VITE_API_URL}/products/publist-stream`
  );

  evtSource.onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log("New event:", data);
    queue.add(() => handlePublish(data, 30000));
  };

  evtSource.onerror = (err) => {
    console.error("EventSource failed:", err);
  };
};

const handleListenDeletes = () => {
  const evtSource = new EventSource(
    `${import.meta.env.VITE_API_URL}/products/delete-stream`
  );

  evtSource.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data);
      console.log("[SSE] New event:", data);

      queue.add(() => {
        return new Promise<void>((resolve) => {
          const listener = (msg: any) => {
            if (msg?.type === "delete-done") {
              console.log("[QUEUE] Delete done signal received.");
              chrome.runtime.onMessage.removeListener(listener);
              resolve();
            }
          };
          chrome.runtime.onMessage.addListener(listener);

          // Gửi tới tab có URL khớp
          chrome.tabs.query(
            { url: "https://www.facebook.com/marketplace/you/selling" },
            (tabs) => {
              for (const tab of tabs) {
                if (tab.id) {
                  chrome.tabs.sendMessage(tab.id, {
                    type: "DELETE_STREAM_DATA",
                    payload: data,
                  });
                }
              }
            }
          );
        });
      });
    } catch (err) {
      console.error("[SSE] Parse error:", err);
    }
  };

  evtSource.onerror = (err) => {
    console.error("[SSE] Connection failed:", err);
  };

  console.log("[SSE] Listening for delete-stream events...");
};

function ensureMarketplaceSellingTab() {
  const targetUrl = "https://www.facebook.com/marketplace/you/selling";

  console.log({ targetUrl });
  chrome.tabs.query({}, (tabs) => {
    const existingTab = tabs.find(
      (tab) => tab.url && tab.url.startsWith(targetUrl)
    );

    if (existingTab) {
      // Nếu đã có thì refresh lại
      chrome.tabs.reload((existingTab as any).id);
    } else {
      // Nếu chưa có thì mở mới
      chrome.tabs.create({ url: targetUrl });
    }
  });
}

const init = async () => {
  handleListenPublists();
  handleListenDeletes();
  ensureMarketplaceSellingTab();
};

chrome.runtime.onMessage.addListener((message, sender) => {
  if (message.type === "close-tab") {
    const tabId = sender.tab?.id;
    if (tabId) chrome.tabs.remove(tabId);
  }
});

init();
