import { useCallback, useMemo } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useClient } from 'hooks/useClient';
import { useAuth } from 'hooks/useAuth';

const QUERY_KEY = ['DOCK'];

type DockItemLike = {
  to: string;
};

export function useDock<T extends DockItemLike>(allDockItems: T[], defaultPaths?: string[]) {
  const client = useClient();
  const { isAuthenticated } = useAuth();
  const queryClient = useQueryClient();

  const { data: dockPaths = null } = useQuery<string[] | null>({
    queryKey: QUERY_KEY,
    enabled: isAuthenticated,
    queryFn: () => client.get<string[] | null>('/dock'),
    staleTime: Infinity,
  });

  const fallbackPaths = useMemo(() => defaultPaths ?? allDockItems.map((i) => i.to), [defaultPaths, allDockItems]);
  const activePaths = dockPaths ?? fallbackPaths;

  const items = useMemo(() => {
    const byPath = new Map(allDockItems.map((item) => [item.to, item]));
    return activePaths.map((path) => byPath.get(path)).filter((item): item is T => !!item);
  }, [activePaths, allDockItems]);

  const allItems = allDockItems;

  const setItems = useCallback(
    (paths: string[]) => {
      queryClient.setQueryData(QUERY_KEY, paths);
      client.put('/dock', paths);
    },
    [client, queryClient],
  );

  const reset = useCallback(() => {
    queryClient.setQueryData(QUERY_KEY, null);
    client.put('/dock', null);
  }, [client, queryClient]);

  return { items, allItems, setItems, reset };
}
