import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  createService,
  updateService,
  deleteService,
  getService,
  getServiceList,
  CreateServiceDto,
} from "../services/api/performanceService";
import { useAuth } from "@/shared/context/AuthContext";
import { useUnit } from "@/user-management/hooks/useUnit";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { useNavigate, useParams } from "react-router-dom";

//  Query Keys
const SERVICE_KEYS = {
  all: ["services"] as const,
  list: (id: string) => ["services", "list", id] as const,
  detail: (id: string) => ["services", id] as const,
};

//  GET SINGLE SERVICE
export function useService(id: string) {
  return useQuery({
    queryKey: SERVICE_KEYS.detail(id),
    queryFn: () => getService(id),
    enabled: !!id,
  });
}

//  GET SERVICE LIST
export function useServiceList(
  organizationId: string,
  serviceCategoryId?: string,
  parentServiceId?: string
) {
  // react-query
  const queryKey = [
    ...SERVICE_KEYS.list(organizationId as string),
    ...(serviceCategoryId ? [serviceCategoryId] : []),
    ...(parentServiceId ? [parentServiceId] : []),
  ];

  return useQuery({
    queryKey,
    queryFn: () =>
      getServiceList(
        organizationId as string,
        serviceCategoryId,
        parentServiceId
      ),
    enabled: !!organizationId, // only fetch when organizationId exists
  });
}

// 🎯 UNIFIED HOOK - Returns all service operations in one object
export function useServiceMutations() {
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);
  const navigate = useNavigate();

  const createMutation = useMutation({
    mutationFn: (data: CreateServiceDto) => createService(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: SERVICE_KEYS.all });
      toast("Service created successfully");
      navigate(`/performance-management/services`);
    },
    onError: (exception) => {
      queryClient.invalidateQueries({ queryKey: SERVICE_KEYS.all });
      handleError(exception);
    },
  });

  const updateMutation = useMutation({
    mutationFn: (data: CreateServiceDto) => updateService(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: SERVICE_KEYS.all });
      toast("Service updated successfully");
      navigate(`/performance-management/services`);
    },
    onError: (exception) => {
      queryClient.invalidateQueries({ queryKey: SERVICE_KEYS.all });
      handleError(exception);
    },
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) => deleteService(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: SERVICE_KEYS.all });
      toast("Service deleted successfully");
      navigate(`/performance-management/services`);
    },
    onError: (exception) => {
      queryClient.invalidateQueries({ queryKey: SERVICE_KEYS.all });
      handleError(exception);
    },
  });

  return {
    create: createMutation,
    update: updateMutation,
    delete: deleteMutation,
  };
}
