"use client";

import { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

import { NOTIFICATIONS_QUERY_KEY } from "@/components/shared/NotificationSync";
import { deleteNotifications, getNotifications, markNotificationsRead, openNotification } from "@/features/notification/services/notificationApi";
import type { NotificationActionType } from "@/features/notification/notificationRecord";
import { useAuthStore } from "@/store/authStore";
import { useLanguageStore } from "@/store/languageStore";
import { useNotificationStore } from "@/store/notificationStore";
import { useWindowWidth } from "@/hooks/useWindowWidth";
import { toastApiError } from "@/lib/api/toastApiError";
import { formatNotificationDate as formatDate } from "@/features/notification/notificationDate";

type NotificationType = "message" | "registration" | "reminder";

export interface NotificationItem {
  id: string;
  type: NotificationType;
  message_en: string;
  message_ar: string;
  title_en: string;
  title_ar: string;
  date: string;
  createdAt?: string | null;
  read: boolean;
  /** Set when the notice points at an opportunity or event. */
  target: { type: NotificationActionType; id: number } | null;
}

const TARGET_PATHS: Record<NotificationActionType, string> = {
  volunteer_opportunity: "/volunteer-event-detail",
  learn_serve_opportunity: "/learn-share-event-detail",
  event: "/event-details",
};


/**
 * The notification list's data and the three actions on it.
 *
 * The read/delete handlers write to the Zustand store as well as the API: the
 * header's unread badge reads the store, so it would otherwise lag a refetch.
 */
export function useNotifications() {
  const { t } = useTranslation();
  const queryClient = useQueryClient();
  const [open, setOpen] = useState(false);
  const selectedLanguage = useLanguageStore((s) => s.language);
  const [selectedNotification, setSelectedNotification] =
    useState<NotificationItem | null>(null);

  // Shares its cache entry with NotificationSync's poller, so this only
  // re-fetches when the cached page is stale.
  const authToken = useAuthStore((s) => s.user?.auth_token);
  const { data, isLoading, isError, error, refetch } = useQuery({
    queryKey: NOTIFICATIONS_QUERY_KEY,
    queryFn: getNotifications,
    enabled: Boolean(authToken),
  });
  const apiNotifications = data?.data;

  // Local store updates keep the header badge in sync without waiting for a poll.
  const updateReadStatus = useNotificationStore((s) => s.updateReadStatus);
  const markAllRead = useNotificationStore((s) => s.markAllRead);
  const removeNotification = useNotificationStore((s) => s.removeNotification);

  const refetchNotifications = () =>
    queryClient.invalidateQueries({ queryKey: NOTIFICATIONS_QUERY_KEY });

  const markReadMutation = useMutation({ mutationFn: markNotificationsRead });
  const deleteMutation = useMutation({ mutationFn: deleteNotifications });

  const windowWidth = useWindowWidth();


  const notifications: NotificationItem[] = useMemo(() => {
    if (!Array.isArray(apiNotifications)) {
      return [];
    }

    // The API nests the localized copy under a `notification` object:
    // { id, is_read, created_at, notification: { title_en, title_ar, message_en, message_ar } }
    return apiNotifications.map((item) => {
      let type: NotificationType = "message";
      const messageEnLower = item.notification?.message_en?.toLowerCase() || "";
      if (messageEnLower.includes("registered")) {
        type = "registration";
      } else if (messageEnLower.includes("reminder")) {
        type = "reminder";
      }

      return {
        id: item.id.toString(),
        type,
        message_en: item.notification?.message_en || "",
        message_ar: item.notification?.message_ar || "",
        title_en: item.notification?.title_en || "",
        title_ar: item.notification?.title_ar || "",
        /* `created_at` is nullable on the resource
           (`$this->created_at?->toIso8601String()`), and `formatDate` takes a
           string — so an empty date renders as empty rather than "Invalid
           Date". */
        createdAt: item.created_at,
        date: item.created_at ? formatDate(item.created_at, selectedLanguage) : "",
        read: item.is_read,
        target:
          item.notification?.action_type && item.notification.entity_id
            ? { type: item.notification.action_type, id: item.notification.entity_id }
            : null,
      };
    });
  }, [apiNotifications, selectedLanguage]);

  const [displayNotifications, setDisplayNotifications] =
    useState<NotificationItem[]>(notifications);

  /*
   * Follow the fetched list during render, not from an effect.
   *
   * `displayNotifications` is written optimistically when a notification is
   * marked read, so it is not purely derived — but it must re-sync when the
   * query returns a new list. `notifications` is a `useMemo`, so the identity
   * comparison below changes exactly when its inputs do.
   */
  const [prevNotifications, setPrevNotifications] = useState(notifications);
  if (notifications !== prevNotifications) {
    setPrevNotifications(notifications);
    setDisplayNotifications(notifications);
  }

  const router = useRouter();
  const openMutation = useMutation({ mutationFn: openNotification });
  const markOpenedMutation = useMutation({ mutationFn: openNotification });

  /*
   * Reading a notice marks it read: `POST /notifications/{id}/open/` is the
   * backend's "opening a notification" call and sets `is_read`. Before, the
   * body could be read in full while the row and the bell kept it unread
   * until the eye icon was pressed as well.
   */
  const openNotificationModal = (notification: NotificationItem) => {
    setSelectedNotification(notification);
    setOpen(true);
    if (notification.read) return;
    markOpenedMutation.mutate(notification.id, {
      onSuccess: () => {
        setDisplayNotifications((prev) =>
          prev.map((row) => (row.id === notification.id ? { ...row, read: true } : row))
        );
        updateReadStatus(parseInt(notification.id), true);
        refetchNotifications();
      },
    });
  };

  /** Opens what the notice points at; a deleted item says so instead. */
  const openTarget = async (notification: NotificationItem) => {
    const target = notification.target;
    if (!target) return;
    try {
      const response = await openMutation.mutateAsync(notification.id);
      updateReadStatus(parseInt(notification.id), true);
      refetchNotifications();
      if (response?.data?.available === false) {
        toast.info(t("COMMON.NOTIFICATION_ITEM_UNAVAILABLE"));
        return;
      }
      setOpen(false);
      router.push(`${TARGET_PATHS[target.type]}/${target.id}`);
    } catch (err) {
      toastApiError(err, selectedLanguage, t("COMMON.NOTIFICATION_ITEM_UNAVAILABLE"));
    }
  };

  const markAsRead = async (id: string, currentReadStatus: boolean) => {
    try {
      const newReadStatus = !currentReadStatus;
      await markReadMutation.mutateAsync({
        notification_ids: [parseInt(id)],
        is_read: newReadStatus,
      });

      // Update local display state
      setDisplayNotifications((prev) =>
        prev.map((notification) =>
          notification.id === id
            ? { ...notification, read: newReadStatus }
            : notification
        )
      );

      // Update the shared store so the header badge reacts immediately
      updateReadStatus(parseInt(id), newReadStatus);

      // Still refetch for consistency
      refetchNotifications();

      toast.success(
        t(
          newReadStatus
            ? "COMMON.TOAST.NOTIFICATION_MARKED_SUCCESS"
            : "COMMON.TOAST.NOTIFICATION_MARKED_UNREAD_SUCCESS"
        )
      );
    } catch (err) {
      console.error("Failed to update notification read status:", err);
      toastApiError(err, selectedLanguage, t("COMMON.TOAST.NOTIFICATION_MARK_FAILED"));
    }
  };

  const markAllAsRead = async () => {
    try {
      await markReadMutation.mutateAsync({ mark_all: true, is_read: true });

      setDisplayNotifications((prev) =>
        prev.map((notification) => ({ ...notification, read: true }))
      );

      // Zeroes the header badge without waiting for the next poll
      markAllRead();
      refetchNotifications();

      toast.success(t("COMMON.TOAST.NOTIFICATION_MARKED_SUCCESS"));
    } catch (err) {
      console.error("Failed to mark all notifications as read:", err);
      toastApiError(err, selectedLanguage, t("COMMON.TOAST.NOTIFICATION_MARK_FAILED"));
    }
  };

  const removeNotificationHandler = async (id: string) => {
    try {
      // DELETE /notifications/{id}/ removes a single notification.
      await deleteMutation.mutateAsync(parseInt(id));

      // Update local display state
      setDisplayNotifications((prev) =>
        prev.filter((notification) => notification.id !== id)
      );

      // Update the shared store so the header badge reacts immediately
      removeNotification(parseInt(id));

      // Still refetch for consistency
      refetchNotifications();

      toast.success(t("COMMON.TOAST.NOTIFICATION_DELETE_SUCCESS"));
    } catch (err) {
      console.error("Failed to delete notification:", err);
      toastApiError(err, selectedLanguage, t("COMMON.TOAST.NOTIFICATION_DELETE_FAILED"));
    }
  };
  return {
    isLoading,
    isError: isError && !Array.isArray(apiNotifications),
    error,
    refetch,
    queryClient,
    open,
    setOpen,
    selectedLanguage,
    selectedNotification,
    setSelectedNotification,
    authToken,
    apiNotifications,
    updateReadStatus,
    markAllRead,
    removeNotification,
    refetchNotifications,
    markReadMutation,
    deleteMutation,
    windowWidth,
    notifications,
    displayNotifications,
    setDisplayNotifications,
    openNotificationModal,
    openTarget,
    isOpeningTarget: openMutation.isPending,
    markAsRead,
    markAllAsRead,
    removeNotificationHandler,
  };
}
