import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import {
  PositionConfiguration,
  PositionConfigurationPayload,
  fetchPositionConfigurationByPositionId,
  savePositionConfiguration,
} from "../services/positionConfigurationService";

export const usePositionConfigurationByPositionId = (positionId: string) => {
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  const {
    data: configuration,
    isLoading,
    isError,
    error,
    refetch,
    isFetching,
  } = useQuery({
    queryKey: ["position-configuration", positionId],
    queryFn: () => fetchPositionConfigurationByPositionId(positionId),
    enabled: !!positionId,
  });

  const saveMutation = useMutation({
    mutationFn: (payload: PositionConfigurationPayload) =>
      savePositionConfiguration(payload, configuration?.id),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["position-configuration", positionId],
      });
      toast.success(
        t(
          "setting.configSaved",
          "Position configuration saved successfully",
        ),
      );
    },
    onError: (saveError) => {
      handleError(saveError);
    },
  });

  return {
    configuration: configuration ?? null,
    isLoading: isLoading || isFetching,
    isError,
    error,
    refetch,
    saveConfiguration: saveMutation.mutate,
    saveConfigurationAsync: saveMutation.mutateAsync,
    isSaving: saveMutation.isPending,
  };
};

/** @deprecated Use usePositionConfigurationByPositionId instead */
export const usePositionConfigurations = (positionId: string) => {
  const result = usePositionConfigurationByPositionId(positionId);

  return {
    configurations: result.configuration ? [result.configuration] : [],
    isLoading: result.isLoading,
    isError: result.isError,
    error: result.error,
    refetch: result.refetch,
    createConfiguration: (
      payload: PositionConfigurationPayload,
      options?: { onSuccess?: () => void },
    ) => {
      result.saveConfiguration(payload, {
        onSuccess: () => options?.onSuccess?.(),
      });
    },
    updateConfiguration: (
      {
        payload,
      }: {
        id?: string;
        payload: PositionConfigurationPayload;
      },
      options?: { onSuccess?: () => void },
    ) => {
      result.saveConfiguration(payload, {
        onSuccess: () => options?.onSuccess?.(),
      });
    },
    deleteConfiguration: () => undefined,
    isCreating: result.isSaving,
    isUpdating: result.isSaving,
    isDeleting: false,
  };
};

export const usePositionConfiguration = (positionId: string) => {
  return useQuery({
    queryKey: ["position-configuration", positionId],
    queryFn: () => fetchPositionConfigurationByPositionId(positionId),
    enabled: !!positionId,
  });
};

export type { PositionConfiguration };
