import { useState } from "react";
import {
  saveToken,
  getNotifications,
  markAsRead,
  type SaveTokenData,
  type MarkReadData,
  type NotificationFilters,
  type NotificationListResponse,
  type SaveTokenResponse,
  type MarkReadResponse,
} from "../../services/notificationService";
import { handleToastError, customizeToast } from "../../utils";

function useNotificationService() {
  const [loading, setLoading] = useState(false);

  // Save FCM Token
  const saveTokenAsync = async (data: SaveTokenData) => {
    try {
      setLoading(true);
      const response = await saveToken(data);

      // Check if the response indicates success
      if (response?.data?.success !== false) {
        return {
          success: true,
          data: response.data,
          message: response.data?.message || "Token saved successfully",
        };
      } else {
        // Backend returned success: false - handle gracefully (FCM is optional)
        const errorMessage = response.data?.message || "Failed to save token";
        return {
          success: false,
          data: null,
          message: errorMessage,
        };
      }
    } catch (error: any) {
      setLoading(false);
      // Handle network errors or other exceptions - don't throw or log to console (avoids Next.js overlay)
      const errorMessage = error?.response?.data?.message || error.toString();
      return {
        success: false,
        data: null,
        message: errorMessage,
      };
    } finally {
      setLoading(false);
    }
  };

  // Get Notifications
  const getNotificationsAsync = async (filters?: NotificationFilters) => {
    try {
      setLoading(true);
      const response = await getNotifications(filters);

      // Check if the response indicates success
      if (response?.data?.success !== false) {
        return {
          success: true,
          data: response.data,
          message:
            response.data?.message || "Notifications fetched successfully",
        };
      } else {
        // Backend returned success: false, show the backend error message
        const errorMessage =
          response.data?.message || "Failed to fetch notifications";
        handleToastError(errorMessage);
        return {
          success: false,
          data: null,
          message: errorMessage,
        };
      }
    } catch (error: any) {
      setLoading(false);
      // Handle network errors or other exceptions
      const errorMessage = error?.response?.data?.message || error.toString();
      handleToastError(errorMessage);
      return {
        success: false,
        data: null,
        message: errorMessage,
      };
    } finally {
      setLoading(false);
    }
  };

  // Mark Notification as Read
  const markAsReadAsync = async (data: MarkReadData) => {
    try {
      setLoading(true);
      const response = await markAsRead(data);

      // Check if the response indicates success
      if (response?.data?.success !== false) {
        return {
          success: true,
          data: response.data,
          message: response.data?.message || "Notification marked as read",
        };
      } else {
        // Backend returned success: false, show the backend error message
        const errorMessage =
          response.data?.message || "Failed to mark notification as read";
        handleToastError(errorMessage);
        return {
          success: false,
          data: null,
          message: errorMessage,
        };
      }
    } catch (error: any) {
      setLoading(false);
      // Handle network errors or other exceptions
      const errorMessage = error?.response?.data?.message || error.toString();
      handleToastError(errorMessage);
      return {
        success: false,
        data: null,
        message: errorMessage,
      };
    } finally {
      setLoading(false);
    }
  };

  // Mark All Notifications as Read
  const markAllAsReadAsync = async () => {
    try {
      setLoading(true);
      const response = await markAsRead({ mark_all_read: true });

      // Check if the response indicates success
      if (response?.data?.success !== false) {
        return {
          success: true,
          data: response.data,
          message: response.data?.message || "Notification marked as read",
        };
      } else {
        // Backend returned success: false, show the backend error message
        const errorMessage =
          response.data?.message || "Failed to mark notification as read";
        handleToastError(errorMessage);
        return {
          success: false,
          data: null,
          message: errorMessage,
        };
      }
    } catch (error: any) {
      setLoading(false);
      // Handle network errors or other exceptions
      const errorMessage = error?.response?.data?.message || error.toString();
      handleToastError(errorMessage);
      return {
        success: false,
        data: null,
        message: errorMessage,
      };
    } finally {
      setLoading(false);
    }
  };

  return {
    loading,
    saveTokenAsync,
    getNotificationsAsync,
    markAsReadAsync,
    markAllAsReadAsync,
  };
}

export default useNotificationService;
