"use client";

import { useCallback, useEffect } from "react";
import {
  useQuery,
  useQueryClient,
} from "@tanstack/react-query";

import { useCurrentUser } from "@/features/auth/hook/use-current-user";
import {
  NOTIFICATION_SETTING_UPDATED_EVENT,
  useNotificationSetting,
} from "@/features/notification-setting/hook/use-notification-setting";

import {
  getSystemNotifications,
  type SystemNotification,
} from "./system-notifications-service";

export const SYSTEM_NOTIFICATIONS_QUERY_KEY = [
  "system-notifications",
] as const;

const REFRESH_INTERVAL_MS = 30_000;
const NOTIFICATION_PAGE_SIZE = 20;

type UseSystemNotificationsResult = {
  notifications: SystemNotification[];
  unreadCount: number;
  isLoading: boolean;
  error: string | null;
  refetch: () => void;

  systemNotificationEnabled: boolean;
  unreadBadgeEnabled: boolean;
  settingLoading: boolean;
};

export function useSystemNotifications(): UseSystemNotificationsResult {
  const queryClient = useQueryClient();

  const { user } = useCurrentUser();

  const {
    settings,
    loading: settingLoading,
  } = useNotificationSetting();

  const isLoggedIn = Boolean(user?.id);

  const systemNotificationEnabled =
    settings.system.enabled;

  const unreadBadgeEnabled =
    settings.system.unreadBadge;

  const canLoadNotifications =
    isLoggedIn &&
    !settingLoading &&
    systemNotificationEnabled;

  const query = useQuery({
    queryKey: SYSTEM_NOTIFICATIONS_QUERY_KEY,

    queryFn: () =>
      getSystemNotifications({
        page: 1,
        limit: NOTIFICATION_PAGE_SIZE,
        isRead: false,
      }),

    /*
     * System Notification បិទ → មិន call API។
     */
    enabled: canLoadNotifications,

    refetchInterval: canLoadNotifications
      ? REFRESH_INTERVAL_MS
      : false,

    refetchOnWindowFocus:
      canLoadNotifications,

    retry: 1,
  });

  /*
   * បើ System Notification ត្រូវបានបិទ
   * លុប notification cache ដើម្បីឱ្យ UI បង្ហាញ 0។
   */
  useEffect(() => {
    if (
      settingLoading ||
      systemNotificationEnabled
    ) {
      return;
    }

    queryClient.setQueryData(
      SYSTEM_NOTIFICATIONS_QUERY_KEY,
      {
        data: [],
        meta: {
          page: 1,
          limit: 0,
          total: 0,
          unreadCount: 0,
          totalPages: 0,
        },
      },
    );
  }, [
    queryClient,
    settingLoading,
    systemNotificationEnabled,
  ]);

  /*
   * Reload notification នៅពេល notification ត្រូវបាន read
   * ឬ backend data ត្រូវបានផ្លាស់ប្ដូរ។
   */
  useEffect(() => {
    if (!isLoggedIn) {
      return;
    }

    const handleNotificationUpdated = () => {
      if (!systemNotificationEnabled) {
        return;
      }

      void queryClient.invalidateQueries({
        queryKey:
          SYSTEM_NOTIFICATIONS_QUERY_KEY,
      });
    };

    window.addEventListener(
      "system-notification-updated",
      handleNotificationUpdated,
    );

    return () => {
      window.removeEventListener(
        "system-notification-updated",
        handleNotificationUpdated,
      );
    };
  }, [
    isLoggedIn,
    queryClient,
    systemNotificationEnabled,
  ]);

  /*
   * ពេល Save Notification Setting៖
   * - បើបើក System Notification → Fetch list
   * - បើបិទ → Clear list
   */
  useEffect(() => {
    const handleSettingUpdated = () => {
      void queryClient.invalidateQueries({
        queryKey:
          SYSTEM_NOTIFICATIONS_QUERY_KEY,
      });
    };

    window.addEventListener(
      NOTIFICATION_SETTING_UPDATED_EVENT,
      handleSettingUpdated,
    );

    return () => {
      window.removeEventListener(
        NOTIFICATION_SETTING_UPDATED_EVENT,
        handleSettingUpdated,
      );
    };
  }, [queryClient]);

  const queryRefetch = query.refetch;

  const refetch = useCallback(() => {
    if (!canLoadNotifications) {
      return;
    }

    void queryRefetch();
  }, [
    canLoadNotifications,
    queryRefetch,
  ]);

  return {
    notifications:
      systemNotificationEnabled
        ? query.data?.data ?? []
        : [],

    unreadCount:
      systemNotificationEnabled &&
      unreadBadgeEnabled
        ? Math.max(
            query.data?.meta.unreadCount ?? 0,
            0,
          )
        : 0,

    isLoading:
      settingLoading ||
      (canLoadNotifications &&
        query.isLoading),

    error:
      query.error &&
      systemNotificationEnabled
        ? query.error instanceof Error
          ? query.error.message
          : "Unable to load notifications."
        : null,

    refetch,

    systemNotificationEnabled,
    unreadBadgeEnabled,
    settingLoading,
  };
}