"use client";

import { useQuery } from "@tanstack/react-query";
import { useEffect } from "react";
import * as api from "../service/MenuService";
import { useParams } from "next/navigation";
import { hasAuthToken } from "@/lib/api/func";
import {
  getPersistedCategoriesData,
  getPersistedMenuData,
  setPersistedCategoriesData,
  setPersistedMenuData,
} from "@/lib/helpers/themeCache";

export const useGetFoods = () => {
  const { name } = useParams<{ name: string }>();
  const query = useQuery({
    queryKey: ["menu", name],
    queryFn: async () => {
      const data = await api.getFoods(name);
      setPersistedMenuData(name, data);
      return data;
    },
    enabled: !!name,
    staleTime: 5 * 60_000,
    refetchOnMount: "always",
    placeholderData: () => (name ? getPersistedMenuData(name) : undefined),
  });

  useEffect(() => {
    if (name && query.data) {
      setPersistedMenuData(name, query.data);
    }
  }, [name, query.data]);

  return query;
};

export const useGetCategories = () => {
  const { name } = useParams<{ name: string }>();
  const query = useQuery({
    queryKey: ["categories", name],
    queryFn: async () => {
      const data = await api.getCategories(name);
      setPersistedCategoriesData(name, data);
      return data;
    },
    enabled: !!name,
    staleTime: 5 * 60_000,
    refetchOnMount: "always",
    placeholderData: () => (name ? getPersistedCategoriesData(name) : undefined),
  });

  useEffect(() => {
    if (name && query.data) {
      setPersistedCategoriesData(name, query.data);
    }
  }, [name, query.data]);

  return query;
};

export const useGetNotificationsCount = () => {
  return useQuery({
    queryKey: ["notifications-count"],
    queryFn: api.getNotificationsCount,
    enabled: hasAuthToken(),
  });
};

export const useGetSliders = () => {
  const { name } = useParams<{ name: string }>();
  return useQuery({
    queryKey: ["sliders", name],
    queryFn: () => api.getSliders(name),
    enabled: !!name,
    staleTime: 5 * 60_000,
    refetchOnMount: "always",
  });
};
