import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { containerService } from './container.service';
import { toast } from 'sonner';

export const CONTAINERS_QUERY_KEY = ['containers'];

export function useContainers() {
  return useQuery({
    queryKey: CONTAINERS_QUERY_KEY,
    queryFn: () => containerService.getContainers(),
  });
}

export function useContainersByWagon(wagonId: string) {
  return useQuery({
    queryKey: [...CONTAINERS_QUERY_KEY, 'wagon', wagonId],
    queryFn: () => containerService.getContainersByWagon(wagonId),
    enabled: !!wagonId,
  });
}

export function useContainerMutations() {
  const queryClient = useQueryClient();

  const createContainer = useMutation({
    mutationFn: (data: any) => containerService.createContainer(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: CONTAINERS_QUERY_KEY });
      toast.success('Container created successfully');
    },
  });

  const updateContainer = useMutation({
    mutationFn: ({ id, data }: { id: string; data: any }) => containerService.updateContainer(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: CONTAINERS_QUERY_KEY });
      toast.success('Container updated successfully');
    },
  });

  const deleteContainer = useMutation({
    mutationFn: (id: string) => containerService.deleteContainer(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: CONTAINERS_QUERY_KEY });
      toast.success('Container deleted successfully');
    },
  });

  return { createContainer, updateContainer, deleteContainer };
}

export function useUnassignContainer() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => containerService.unassignFromWagon(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: CONTAINERS_QUERY_KEY });
      toast.success('Container unassigned from wagon');
    },
  });
}

export function useAssignContainerToWagon() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ containerId, wagonId, position }: { containerId: string; wagonId: string; position?: number }) =>
      containerService.assignToWagon(containerId, wagonId, position),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: CONTAINERS_QUERY_KEY });
      toast.success('Container assigned to wagon');
    },
  });
}