import { useEffect } from "react";
import { io } from "socket.io-client";
import { useQueryClient } from "@tanstack/react-query";
import {
  getListNotificationsQueryKey,
  getGetHomeStatsQueryKey,
  getListMyServiceOrdersQueryKey,
  getListIncomingServiceOrdersQueryKey,
  getListAppsQueryKey,
  getGetMeQueryKey,
  getListRolesQueryKey,
  getListPermissionsQueryKey,
  getGetRolePermissionsQueryKey,
  getGetRolePermissionAuditQueryKey,
  getGetRoleUsageQueryKey,
} from "@workspace/api-client-react";
import { useAuth } from "@/contexts/AuthContext";

const BASE = import.meta.env.BASE_URL.replace(/\/$/, "");

export function useNotificationsSocket() {
  const { user } = useAuth();
  const queryClient = useQueryClient();

  useEffect(() => {
    if (!user) return;

    const socket = io(window.location.origin, {
      path: `${BASE}/api/socket.io`,
    });

    socket.on("notification_created", (payload?: { type?: string }) => {
      queryClient.invalidateQueries({ queryKey: getListNotificationsQueryKey() });
      queryClient.invalidateQueries({ queryKey: getGetHomeStatsQueryKey() });
      if (payload?.type === "order") {
        queryClient.invalidateQueries({
          queryKey: getListMyServiceOrdersQueryKey(),
        });
        queryClient.invalidateQueries({
          queryKey: getListIncomingServiceOrdersQueryKey(),
        });
      }
    });

    socket.on("order_updated", () => {
      queryClient.invalidateQueries({
        queryKey: getListMyServiceOrdersQueryKey(),
      });
      queryClient.invalidateQueries({
        queryKey: getListIncomingServiceOrdersQueryKey(),
      });
    });

    socket.on("order_deleted", () => {
      queryClient.invalidateQueries({
        queryKey: getListMyServiceOrdersQueryKey(),
      });
      queryClient.invalidateQueries({
        queryKey: getListIncomingServiceOrdersQueryKey(),
      });
    });

    socket.on("order_incoming_changed", () => {
      queryClient.invalidateQueries({
        queryKey: getListIncomingServiceOrdersQueryKey(),
      });
    });

    socket.on("apps_changed", () => {
      queryClient.invalidateQueries({ queryKey: getListAppsQueryKey() });
      queryClient.invalidateQueries({ queryKey: getGetMeQueryKey() });
    });

    socket.on(
      "executive_meetings_changed",
      (payload?: { date?: string }) => {
        if (typeof payload?.date === "string" && payload.date.length > 0) {
          queryClient.invalidateQueries({
            queryKey: ["/api/executive-meetings", payload.date],
          });
        } else {
          queryClient.invalidateQueries({
            queryKey: ["/api/executive-meetings"],
          });
        }
      },
    );

    socket.on("executive_meeting_notifications_changed", () => {
      queryClient.invalidateQueries({
        queryKey: ["/api/executive-meetings/notifications"],
      });
      queryClient.invalidateQueries({
        queryKey: ["/api/executive-meetings/requests"],
      });
      queryClient.invalidateQueries({
        queryKey: ["/api/executive-meetings/tasks"],
      });
    });

    socket.on(
      "role_permissions_changed",
      (payload?: { roleId?: number }) => {
        queryClient.invalidateQueries({ queryKey: getGetMeQueryKey() });
        queryClient.invalidateQueries({ queryKey: getListPermissionsQueryKey() });
        queryClient.invalidateQueries({ queryKey: getListRolesQueryKey() });
        const roleId = payload?.roleId;
        if (typeof roleId === "number") {
          queryClient.invalidateQueries({
            queryKey: getGetRolePermissionsQueryKey(roleId),
          });
          queryClient.invalidateQueries({
            queryKey: getGetRolePermissionAuditQueryKey(roleId),
          });
          queryClient.invalidateQueries({
            queryKey: getGetRoleUsageQueryKey(roleId),
          });
        }
      },
    );

    return () => {
      socket.disconnect();
    };
  }, [user, queryClient]);
}
