import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
  addShoppingItem,
  CustomRange,
  decreaseQuantity,
  fetchCustomRanges,
  fetchShoppingList,
  increaseQuantity,
  removeCustomRange,
  removeShoppingItem,
  saveCustomRange,
  setQuantity,
  ShoppingListPayload,
  toggleChecked,
  toggleOwned,
} from '../../../api/shoppingList';

// `to` : borne de fin personnalisée (encadrement de dates custom, voir
// CustomRangeModal.tsx/ShoppingListScreen.tsx) — `null`/absente = semaine de 7 jours à
// partir de `week` (navigation normale).
const queryKey = (week: string, to?: string | null) => ['shopping-list', week, to ?? ''];

export function useShoppingList(week: string, to?: string | null) {
  return useQuery({
    queryKey: queryKey(week, to),
    queryFn: () => fetchShoppingList(week, to),
  });
}

function useShoppingListMutation<TArgs>(week: string, to: string | null | undefined, mutationFn: (args: TArgs) => Promise<ShoppingListPayload>) {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn,
    onSuccess: (payload: ShoppingListPayload) => {
      queryClient.setQueryData(queryKey(week, to), payload);
    },
  });
}

export function useAddShoppingItem(week: string, to?: string | null) {
  return useShoppingListMutation<{ name: string; aisle?: string }>(week, to, ({ name, aisle }) => addShoppingItem(week, name, aisle, to));
}

export function useRemoveShoppingItem(week: string, to?: string | null) {
  return useShoppingListMutation<number>(week, to, (id) => removeShoppingItem(id, week, to));
}

export function useToggleOwned(week: string, to?: string | null) {
  return useShoppingListMutation<number>(week, to, (id) => toggleOwned(id, week, to));
}

export function useToggleChecked(week: string, to?: string | null) {
  return useShoppingListMutation<number>(week, to, (id) => toggleChecked(id, week, to));
}

export function useIncreaseQuantity(week: string, to?: string | null) {
  return useShoppingListMutation<number>(week, to, (id) => increaseQuantity(id, week, to));
}

export function useDecreaseQuantity(week: string, to?: string | null) {
  return useShoppingListMutation<number>(week, to, (id) => decreaseQuantity(id, week, to));
}

export function useSetQuantity(week: string, to?: string | null) {
  return useShoppingListMutation<{ id: number; value: number }>(week, to, ({ id, value }) => setQuantity(id, week, value, to));
}

const customRangesQueryKey = ['shopping-list-custom-ranges'];

export function useCustomRanges() {
  return useQuery({
    queryKey: customRangesQueryKey,
    queryFn: fetchCustomRanges,
  });
}

function useCustomRangeMutation<TArgs>(mutationFn: (args: TArgs) => Promise<{ ranges: CustomRange[] }>) {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn,
    onSuccess: (payload: { ranges: CustomRange[] }) => {
      queryClient.setQueryData(customRangesQueryKey, payload);
    },
  });
}

// Enregistre (ou réutilise) le créneau dès qu'il est appliqué — voir CustomRangeModal.tsx,
// pas de geste "sauvegarder" séparé pour l'utilisateur.
export function useSaveCustomRange() {
  return useCustomRangeMutation<{ start: string; end: string }>(({ start, end }) => saveCustomRange(start, end));
}

export function useRemoveCustomRange() {
  return useCustomRangeMutation<number>((id) => removeCustomRange(id));
}
