import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { Channel, StreamChat } from "stream-chat";
import { useUser } from "../providers/UserStoreProvider";

export const useChannelFromUrl = (client: StreamChat) => {
  const [channel, setChannel] = useState<Channel | null>(null);
  const { channelId } = useParams();
  useEffect(() => {
    if (channelId) {
      const channel = client.channel("messaging", channelId);
      channel.watch();
      setChannel(channel);
    } else {
      setChannel(null);
    }
  }, [channelId, client]);
  return { channel, isChannelInUrl: !!channelId };
};

export const useTabloDiscussionUnread = (tabloId?: string) => {
  const user = useUser();
  const [hasUnread, setHasUnread] = useState(false);

  useEffect(() => {
    if (!tabloId || !user.id || !user.streamToken) {
      setHasUnread(false);
      return;
    }

    const apiKey = import.meta.env.VITE_STREAM_CHAT_API_KEY as string;
    const client = StreamChat.getInstance(apiKey);
    let isMounted = true;
    let unsubscribe: (() => void) | undefined;

    const syncUnread = (channel: Channel) => {
      if (!isMounted) return;
      setHasUnread(channel.countUnread() > 0);
    };

    const init = async () => {
      try {
        if (!client.userID) {
          await client.connectUser(
            {
              id: user.id,
              name: user.name ?? "",
            },
            user.streamToken
          );
        } else if (client.userID !== user.id) {
          await client.disconnectUser();
          await client.connectUser(
            {
              id: user.id,
              name: user.name ?? "",
            },
            user.streamToken
          );
        }

        const channels = await client.queryChannels(
          {
            type: "messaging",
            id: { $eq: tabloId },
            members: { $in: [user.id] },
          },
          { last_message_at: -1 },
          { watch: true, state: true, presence: false, limit: 1 }
        );

        const channel = channels[0];
        if (!channel) {
          setHasUnread(false);
          return;
        }

        syncUnread(channel);

        const subscriptions = [
          channel.on("message.new", () => syncUnread(channel)),
          channel.on("message.read", () => syncUnread(channel)),
          channel.on("notification.mark_read", () => syncUnread(channel)),
          channel.on("notification.message_new", () => syncUnread(channel)),
        ];

        unsubscribe = () => {
          subscriptions.forEach((subscription) => {
            subscription.unsubscribe();
          });
        };
      } catch (error) {
        console.error("Error loading tablo unread discussion state:", error);
        if (isMounted) {
          setHasUnread(false);
        }
      }
    };

    void init();

    return () => {
      isMounted = false;
      unsubscribe?.();
    };
  }, [tabloId, user.id, user.name, user.streamToken]);

  return { hasUnread };
};
