import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import {
  createWorkingHours,
  getWorkingHoursList,
  getWorkingHoursByPositionServiceId,
  updateWorkingHours,
  deleteWorkingHours,
} from "../services/api/workingHoursService";
import { CreateWorkingHoursDto } from "../types/workingHoursTypes";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

export const useWorkingHoursList = () => {
  return useQuery({
    queryKey: ["workingHours"],
    queryFn: getWorkingHoursList,
  });
};

export const useWorkingHoursByPositionService = (positionServiceId: string) => {
  return useQuery({
    queryKey: ["workingHours", positionServiceId],
    queryFn: () => getWorkingHoursByPositionServiceId(positionServiceId),
    enabled: !!positionServiceId,
  });
};

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

  const create = useMutation({
    mutationFn: (data: CreateWorkingHoursDto) => createWorkingHours(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["workingHours"] });
      toast.success(
        t("workingHours.createdSuccessfully", "Working hours created successfully")
      );
    },
    onError: (error: any) => {
      handleError(error);
    },
  });

  const update = useMutation({
    mutationFn: ({ id, data }: { id: string; data: CreateWorkingHoursDto }) =>
      updateWorkingHours(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["workingHours"] });
      toast.success(
        t("workingHours.updatedSuccessfully", "Working hours updated successfully")
      );
    },
    onError: (error: any) => {
      handleError(error);
    },
  });

  const deleteHours = useMutation({
    mutationFn: (id: string) => deleteWorkingHours(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["workingHours"] });
      toast.success(
        t("workingHours.deletedSuccessfully", "Working hours deleted successfully")
      );
    },
    onError: (error: any) => {
      handleError(error);
    },
  });

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