import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import {
  createPasswordSettings,
  getPasswordSettings,
  updatePasswordSettings,
  deletePasswordSettings,
  PasswordSettings,
} from "../services/api/passwordSettingsService";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

export const usePasswordSettingsQuery = () =>
  useQuery({
    queryKey: ["passwordSettings"],
    queryFn: () => getPasswordSettings(),
    staleTime: 30_000,
    refetchOnWindowFocus: false,
    retry: 1,
  });

export const usePasswordSettingsMutations = () => {
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  const update = useMutation({
    mutationFn: (payload: PasswordSettings) => updatePasswordSettings(payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["passwordSettings"] });
      toast.success(
        t("passwordSettings.updated", "Password settings updated successfully")
      );
    },
    onError: (error: any) => {
      handleError(error);
    },
  });

  const create = useMutation({
    mutationFn: (payload: PasswordSettings) => createPasswordSettings(payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["passwordSettings"] });
      toast.success(
        t("passwordSettings.created", "Password settings created successfully")
      );
    },
    onError: (error: any) => {
      handleError(error);
    },
  });

  const delete_mutation = useMutation({
    mutationFn: (id: string) => deletePasswordSettings(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["passwordSettings"] });
      toast.success(
        t("passwordSettings.deleted", "Password settings deleted successfully")
      );
    },
    onError: (error: any) => {
      console.error("Delete mutation error:", error);
      handleError(error);
    },
  });

  return { update, create, delete: delete_mutation };
};
