import { useCallback, useEffect, useRef } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useClient } from 'hooks/useClient';
import { useAuth } from 'hooks/useAuth';
import type { UserState } from './useSettings';

const QUERY_KEY = ['DASHBOARD_STATE'];

export function useDashboardState<T>(key: string, defaultValue: T) {
  const client = useClient();
  const { isAuthenticated } = useAuth();
  const queryClient = useQueryClient();
  const clientRef = useRef(client);
  clientRef.current = client;

  const { data: state = {}, isSuccess } = useQuery<UserState>({
    queryKey: QUERY_KEY,
    enabled: isAuthenticated,
    queryFn: () => client.get<UserState>('/dashboards'),
    staleTime: Infinity,
  });

  // Seed default to backend when key is missing after initial fetch
  const seededKeyRef = useRef<string | null>(null);
  useEffect(() => {
    if (!isSuccess || seededKeyRef.current === key) return;
    seededKeyRef.current = key;

    const currentState = queryClient.getQueryData<UserState>(QUERY_KEY) ?? {};
    if (!(key in currentState)) {
      queryClient.setQueryData(QUERY_KEY, { ...currentState, [key]: defaultValue });
      clientRef.current.patch('/dashboards', { [key]: defaultValue }).catch(() => { });
    }
  }, [isSuccess, key, defaultValue, queryClient]);

  const value = key in state ? (state[key] as T) : defaultValue;

  const setValue = useCallback(
    (update: T | ((prev: T) => T)) => {
      const currentState = queryClient.getQueryData<UserState>(QUERY_KEY) ?? {};
      const currentValue = key in currentState ? (currentState[key] as T) : defaultValue;
      const newValue = typeof update === 'function' ? (update as (prev: T) => T)(currentValue) : update;

      queryClient.setQueryData(QUERY_KEY, { ...currentState, [key]: newValue });

      clientRef.current.patch('/dashboards', { [key]: newValue }).catch(() => { });
    },
    [key, defaultValue, queryClient],
  );

  return { key, value, setValue, isLoaded: isSuccess };
}
