import { gql } from "@apollo/client";

import { playNewMessageSound } from "../../utils/soundManager.js";
import { isLeaderTab } from "../../utils/singleTabAudioLeader";

import { CONVERSATION_LIST_QUERY, GET_CONVERSATION_DETAILS } from "../../graphql/conversations.queries";
import { QUERY_ACTIVE_ASSOCIATION_SOUND } from "../../graphql/user.queries";

const logLocal = (message, ...args) => {
  if (import.meta.env.VITE_APP_IS_TEST || !import.meta.env.PROD) {
    console.log(`==================== ${message} ====================`);
    console.dir({ ...args });
  }
};

const safeIsoNow = () => new Date().toISOString();
const isSystemMsid = (msid) => typeof msid === "string" && msid.startsWith("SYS_");

const normalizeConversationForList = (raw, { isoutbound, isSystem } = {}) => {
  const c = raw || {};
  const id = c.id;

  return {
    __typename: "conversations",
    id,
    phone_num: c.phone_num ?? null,
    updated_at: c.updated_at ?? safeIsoNow(),
    unreadcnt: typeof c.unreadcnt === "number" ? c.unreadcnt : 0,
    archived: c.archived ?? false,
    label: c.label ?? null,

    job_conversations: Array.isArray(c.job_conversations)
      ? c.job_conversations.map((jc) => {
          const job = jc?.job || {};
          const jobId = jc?.jobid ?? job?.id ?? null;

          return {
            __typename: "job_conversations",
            jobid: jobId,
            conversationid: jc?.conversationid ?? id ?? null,
            job: {
              __typename: "jobs",
              id: jobId,
              ro_number: job?.ro_number ?? null,
              ownr_fn: job?.ownr_fn ?? null,
              ownr_ln: job?.ownr_ln ?? null,
              ownr_co_nm: job?.ownr_co_nm ?? null
            }
          };
        })
      : [],

    messages_aggregate: c.messages_aggregate || {
      __typename: "messages_aggregate",
      aggregate: {
        __typename: "messages_aggregate_fields",
        count: isoutbound || isSystem ? 0 : 1
      }
    }
  };
};

const CONVERSATION_LIST_ITEM_FRAGMENT = gql`
  fragment _ConversationListItem on conversations {
    id
    phone_num
    updated_at
    unreadcnt
    archived
    label
    job_conversations {
      jobid
      conversationid
      job {
        id
        ro_number
        ownr_fn
        ownr_ln
        ownr_co_nm
      }
    }
    messages_aggregate(where: { read: { _eq: false }, isoutbound: { _eq: false }, is_system: { _eq: false } }) {
      aggregate {
        count
      }
    }
  }
`;

const normalizeMessageForCache = (raw, fallbackConversationId) => {
  const m = raw || {};

  return {
    __typename: "messages",
    id: m.id,
    conversationid: m.conversationid ?? m.conversation?.id ?? fallbackConversationId,

    status: m.status ?? null,
    text: m.text ?? "",
    is_system: typeof m.is_system === "boolean" ? m.is_system : false,
    isoutbound: typeof m.isoutbound === "boolean" ? m.isoutbound : false,
    image: typeof m.image === "boolean" ? m.image : false,
    image_path: m.image_path ?? null,
    userid: m.userid ?? null,
    created_at: m.created_at ?? safeIsoNow(),
    read: typeof m.read === "boolean" ? m.read : false
  };
};

const isConversationDetailsCached = (client, conversationId) => {
  try {
    return !!client.cache.readQuery({
      query: GET_CONVERSATION_DETAILS,
      variables: { conversationId }
    })?.conversations_by_pk;
  } catch {
    return false;
  }
};

const conversationDetailsCached = (client, conversationId) => {
  try {
    const res = client.cache.readQuery({
      query: GET_CONVERSATION_DETAILS,
      variables: { conversationId }
    });
    return !!res?.conversations_by_pk;
  } catch {
    return false;
  }
};

const messageEntityCached = (client, messageId) => {
  const cacheId = client.cache.identify({ __typename: "messages", id: messageId });
  if (!cacheId) return false;

  try {
    client.cache.readFragment({
      id: cacheId,
      fragment: gql`
        fragment _MsgExists on messages {
          id
        }
      `
    });
    return true;
  } catch {
    return false;
  }
};

const enrichConversation = (conversation, { isoutbound, isSystem }) => ({
  ...conversation,
  updated_at: conversation.updated_at || safeIsoNow(),
  unreadcnt: typeof conversation.unreadcnt === "number" ? conversation.unreadcnt : 0,
  archived: conversation.archived ?? false,
  label: conversation.label ?? null,
  job_conversations: conversation.job_conversations || [],
  messages_aggregate: conversation.messages_aggregate || {
    __typename: "messages_aggregate",
    aggregate: {
      __typename: "messages_aggregate_fields",
      count: isoutbound || isSystem ? 0 : 1
    }
  },
  __typename: "conversations"
});

const upsertConversationIntoOffsetZeroList = (client, conversationObj, { isoutbound, isSystem } = {}) => {
  const normalized = normalizeConversationForList(conversationObj, { isoutbound, isSystem });
  if (!normalized?.id) return;

  const convCacheId = client.cache.identify(normalized);
  if (!convCacheId) return;

  client.cache.writeFragment({
    id: convCacheId,
    fragment: CONVERSATION_LIST_ITEM_FRAGMENT,
    data: normalized
  });

  client.cache.modify({
    id: "ROOT_QUERY",
    fields: {
      conversations(existing = [], { args, readField }) {
        if (!args || args.offset !== 0) return existing;

        const archivedEq = args?.where?.archived?._eq;
        if (archivedEq === true) return existing;

        const without = existing.filter((c) => readField("id", c) !== normalized.id);
        return [{ __ref: convCacheId }, ...without];
      }
    }
  });
};

export const registerMessagingHandlers = ({ socket, client, currentUser, bodyshop }) => {
  if (!(socket && client)) return;

  // Coalesce unread refetches (avoid spamming during bursts)
  let unreadRefetchInFlight = null;
  const refetchUnreadCount = () => {
    if (unreadRefetchInFlight) return;

    unreadRefetchInFlight = client
      .refetchQueries({
        include: ["UNREAD_CONVERSATION_COUNT"]
      })
      .catch(() => {
        // best-effort
      })
      .finally(() => {
        unreadRefetchInFlight = null;
      });
  };

  const handleNewMessageSummary = async (message) => {
    const { conversationId, newConversation, existingConversation, isoutbound, msid, updated_at } = message;
    const isSystem = isSystemMsid(msid);

    const isNewMessageSoundEnabled = (clientInstance) => {
      try {
        const email = currentUser?.email;
        if (!email) return true;
        const res = clientInstance.readQuery({
          query: QUERY_ACTIVE_ASSOCIATION_SOUND,
          variables: { email }
        });
        const flag = res?.associations?.[0]?.new_message_sound;
        return flag === true;
      } catch {
        return true;
      }
    };

    logLocal("handleNewMessageSummary - Start", { message, isNew: !existingConversation });

    if (!isoutbound) {
      if (isLeaderTab(bodyshop.id) && isNewMessageSoundEnabled(client)) {
        playNewMessageSound(bodyshop.id);
      }

      // Real-time badge update for affix (best-effort, coalesced)
      if (!isSystem) {
        refetchUnreadCount();
      }
    }

    if (!existingConversation && conversationId) {
      try {
        const cachedConversation = client.cache.readFragment({
          id: client.cache.identify({ __typename: "conversations", id: conversationId }),
          fragment: gql`
            fragment ExistingConversationCheck on conversations {
              id
            }
          `
        });

        if (cachedConversation) {
          logLocal("handleNewMessageSummary - Existing Conversation inferred from cache", { conversationId });
          return handleNewMessageSummary({ ...message, existingConversation: true });
        }
      } catch {
        // Cache miss is normal
      }
    }

    if (!existingConversation && newConversation?.phone_num) {
      try {
        upsertConversationIntoOffsetZeroList(client, newConversation, { isoutbound, isSystem });
      } catch (error) {
        console.error("Error updating cache for new conversation:", error);
      }
      return;
    }

    if (existingConversation && conversationId) {
      try {
        client.cache.modify({
          id: client.cache.identify({ __typename: "conversations", id: conversationId }),
          fields: {
            updated_at: () => updated_at || safeIsoNow(),
            archived: () => false,

            messages_aggregate(cached = null) {
              if (isoutbound || isSystem) return cached;

              const currentCount = cached?.aggregate?.count ?? 0;
              return {
                __typename: "messages_aggregate",
                aggregate: {
                  __typename: "messages_aggregate_fields",
                  count: currentCount + 1
                }
              };
            },

            unreadcnt(cached) {
              if (isoutbound || isSystem) return cached;
              const n = typeof cached === "number" ? cached : 0;
              return n + 1;
            }
          }
        });
      } catch (error) {
        console.error("Error updating cache for existing conversation:", error);
      }
      return;
    }

    logLocal("New Conversation Summary finished without work", { message });
  };

  const handleNewMessageDetailed = (message) => {
    const { conversationId, newMessage } = message;

    logLocal("handleNewMessageDetailed - Start", message);

    if (!conversationId || !isConversationDetailsCached(client, conversationId)) return;

    try {
      const normalized = normalizeMessageForCache(newMessage, conversationId);

      const messageCacheId = client.cache.identify(normalized);
      if (!messageCacheId) {
        console.warn("handleNewMessageDetailed - Could not identify message for cache", {
          conversationId,
          newMessageId: newMessage?.id
        });
        return;
      }

      client.cache.writeFragment({
        id: messageCacheId,
        fragment: gql`
          fragment _IncomingMessage on messages {
            id
            conversationid
            status
            text
            is_system
            isoutbound
            image
            image_path
            userid
            created_at
            read
          }
        `,
        data: normalized
      });

      client.cache.modify({
        id: client.cache.identify({ __typename: "conversations", id: conversationId }),
        fields: {
          messages(existing = [], { readField }) {
            const already = existing.some((ref) => readField("id", ref) === normalized.id);
            if (already) return existing;
            return [...existing, { __ref: messageCacheId }];
          },
          updated_at() {
            return normalized.created_at || safeIsoNow();
          }
        }
      });

      logLocal("handleNewMessageDetailed - Message appended successfully", { conversationId });
    } catch (error) {
      console.error("Error updating conversation messages in cache:", error);
    }
  };

  const handleMessageChanged = (message) => {
    if (!message?.id) return;

    logLocal("handleMessageChanged - Start", message);

    if (!messageEntityCached(client, message.id)) return;

    try {
      const msgCacheId = client.cache.identify({ __typename: "messages", id: message.id });

      client.cache.modify({
        id: msgCacheId,
        fields: {
          status(existing) {
            return message.type === "status-changed" ? (message.status ?? existing) : existing;
          },
          text(existing) {
            return message.type === "text-updated" ? (message.text ?? existing) : existing;
          }
        }
      });

      logLocal("handleMessageChanged - Message updated successfully", {
        messageId: message.id,
        type: message.type
      });
    } catch (error) {
      console.error("handleMessageChanged - Error modifying cache:", error);
    }
  };

  const handleConversationChanged = async (data) => {
    if (!data?.conversationId) return;

    const {
      conversationId,
      type,
      job_conversations,
      messageIds,
      messageIdsMarkedRead,
      lastUnreadMessageId,
      unreadCount,
      ...fields
    } = data;

    logLocal("handleConversationChanged - Start", data);

    const updatedAt = safeIsoNow();
    const detailsCached = conversationDetailsCached(client, conversationId);

    try {
      switch (type) {
        case "conversation-marked-read": {
          refetchUnreadCount();

          if (detailsCached && Array.isArray(messageIds)) {
            messageIds.forEach((id) => {
              if (!messageEntityCached(client, id)) return;
              client.cache.modify({
                id: client.cache.identify({ __typename: "messages", id }),
                fields: { read: () => true }
              });
            });
          }

          client.cache.modify({
            id: client.cache.identify({ __typename: "conversations", id: conversationId }),
            fields: {
              messages_aggregate: () => ({
                __typename: "messages_aggregate",
                aggregate: { __typename: "messages_aggregate_fields", count: 0 }
              }),
              unreadcnt: () => 0,
              updated_at: () => updatedAt
            }
          });

          break;
        }

        case "conversation-marked-unread": {
          refetchUnreadCount();

          const safeUnreadCount = typeof unreadCount === "number" ? unreadCount : 1;
          const idsMarkedRead = Array.isArray(messageIdsMarkedRead) ? messageIdsMarkedRead : [];

          if (detailsCached) {
            idsMarkedRead.forEach((id) => {
              if (!messageEntityCached(client, id)) return;
              client.cache.modify({
                id: client.cache.identify({ __typename: "messages", id }),
                fields: { read: () => true }
              });
            });

            if (lastUnreadMessageId && messageEntityCached(client, lastUnreadMessageId)) {
              client.cache.modify({
                id: client.cache.identify({ __typename: "messages", id: lastUnreadMessageId }),
                fields: { read: () => false }
              });
            }
          }

          client.cache.modify({
            id: client.cache.identify({ __typename: "conversations", id: conversationId }),
            fields: {
              updated_at: () => updatedAt,
              messages_aggregate: () => ({
                __typename: "messages_aggregate",
                aggregate: {
                  __typename: "messages_aggregate_fields",
                  count: safeUnreadCount
                }
              }),
              unreadcnt: () => safeUnreadCount
            }
          });

          break;
        }

        case "conversation-created": {
          // New conversation likely implies new unread inbound message(s)
          refetchUnreadCount();

          const conv = enrichConversation(
            { id: conversationId, job_conversations, ...fields, updated_at: updatedAt },
            { isoutbound: false, isSystem: false }
          );
          upsertConversationIntoOffsetZeroList(client, conv);
          break;
        }

        case "conversation-unarchived":
        case "conversation-archived": {
          // Keep unread badge correct even if archiving affects counts
          refetchUnreadCount();

          await client.refetchQueries({
            include: [CONVERSATION_LIST_QUERY, GET_CONVERSATION_DETAILS]
          });
          break;
        }

        case "tag-added": {
          const formattedJobConversations = (job_conversations || []).map((jc) => ({
            __typename: "job_conversations",
            jobid: jc.jobid || jc.job?.id,
            conversationid: conversationId,
            job: {
              __typename: "jobs",
              id: jc.job?.id,
              ro_number: jc.job?.ro_number,
              ownr_co_nm: jc.job?.ownr_co_nm,
              ownr_fn: jc.job?.ownr_fn,
              ownr_ln: jc.job?.ownr_ln
            }
          }));

          client.cache.modify({
            id: client.cache.identify({ __typename: "conversations", id: conversationId }),
            fields: {
              job_conversations(existing = [], { readField }) {
                const seen = new Set(existing.map((x) => readField("jobid", x)).filter(Boolean));
                const incoming = formattedJobConversations.filter((x) => x.jobid && !seen.has(x.jobid));
                return [...existing, ...incoming];
              }
            }
          });

          break;
        }

        case "tag-removed": {
          const conversationCacheId = client.cache.identify({ __typename: "conversations", id: conversationId });

          client.cache.evict({
            id: conversationCacheId,
            fieldName: "job_conversations"
          });
          client.cache.gc();
          break;
        }

        default: {
          client.cache.modify({
            id: client.cache.identify({ __typename: "conversations", id: conversationId }),
            fields: Object.fromEntries(
              Object.entries(fields).map(([key, value]) => [key, (cached) => (value !== undefined ? value : cached)])
            )
          });
        }
      }
    } catch (error) {
      console.error("Error handling conversation changes:", { type, error });
    }
  };

  const handlePhoneNumberOptedOut = async (data) => {
    const { bodyshopid, phone_number } = data;
    logLocal("handlePhoneNumberOptedOut - Start", data);

    try {
      client.cache.modify({
        id: "ROOT_QUERY",
        fields: {
          phone_number_opt_out(existing = [], { readField }) {
            const exists = existing.some(
              (ref) => readField("phone_number", ref) === phone_number && readField("bodyshopid", ref) === bodyshopid
            );
            if (exists) return existing;

            const newOptOut = {
              __typename: "phone_number_opt_out",
              id: `temporary-${phone_number}-${Date.now()}`,
              bodyshopid,
              phone_number,
              created_at: safeIsoNow(),
              updated_at: safeIsoNow()
            };

            return [...existing, newOptOut];
          }
        },
        broadcast: true
      });

      client.cache.evict({
        id: "ROOT_QUERY",
        fieldName: "phone_number_opt_out",
        args: { bodyshopid, search: phone_number }
      });
      client.cache.gc();
    } catch (error) {
      console.error("Error updating cache for phone number opt-out:", error);
    }
  };

  const handlePhoneNumberOptedIn = async (data) => {
    const { bodyshopid, phone_number } = data;
    logLocal("handlePhoneNumberOptedIn - Start", data);

    try {
      client.cache.modify({
        id: "ROOT_QUERY",
        fields: {
          phone_number_opt_out(existing = [], { readField }) {
            return existing.filter(
              (ref) => !(readField("phone_number", ref) === phone_number && readField("bodyshopid", ref) === bodyshopid)
            );
          }
        },
        broadcast: true
      });

      client.cache.evict({
        id: "ROOT_QUERY",
        fieldName: "phone_number_opt_out",
        args: { bodyshopid, search: phone_number }
      });
      client.cache.gc();
    } catch (error) {
      console.error("Error updating cache for phone number opt-in:", error);
    }
  };

  socket.on("new-message-summary", handleNewMessageSummary);
  socket.on("new-message-detailed", handleNewMessageDetailed);
  socket.on("message-changed", handleMessageChanged);
  socket.on("conversation-changed", handleConversationChanged);
  socket.on("phone-number-opted-out", handlePhoneNumberOptedOut);
  socket.on("phone-number-opted-in", handlePhoneNumberOptedIn);
};

export const unregisterMessagingHandlers = ({ socket }) => {
  if (!socket) return;
  socket.off("new-message-summary");
  socket.off("new-message-detailed");
  socket.off("message-changed");
  socket.off("conversation-changed");
  socket.off("phone-number-opted-out");
  socket.off("phone-number-opted-in");
};
