import { useData } from 'mystique/hooks/useData';
import { useAuth } from 'mystique/hooks/useAuth';
import { useI18n } from 'mystique/hooks/useI18n';
import { TemplateRegistry } from 'mystique/registry/TemplateRegistry';
import { decorateQueryResult } from '../utils/QueryUtils';
import { useEnv } from 'mystique/hooks/useEnv';
import { useEffect } from 'react';

export const useTemplateRender = (
  ...args: any[]
): ((template: string | undefined, additionalData?: any) => string) => {
  const data = useData();
  const auth = useAuth();
  const env = useEnv();
  const currentLocale = useI18n().language?.current;

  let addData = {};

  if (data?.query?.operation?.variables) {
    addData = { ...addData, ...data.query.operation.variables };
  }
  const activeContext = auth.loggedIn
    ? { id: auth.context.current?.contextId, ...auth.context.current?.details }
    : null;

  addData = {
    ...addData,
    env: { ...env },
    activeContext,
    activeUser: auth.loggedIn && {
      locale: currentLocale,
      ...auth.user,
    },
    activeLocation:
      auth.loggedIn && auth.context.level === 'location'
        ? activeContext
        : undefined,
    activeRetailer:
      auth.loggedIn && auth.context.level === 'retailer'
        ? activeContext
        : auth.loggedIn && auth.context.level === 'location'
          ? { id: auth.context.current?.details?.retailerId }
          : undefined,
  };

  addData = args
    ? args.reduce((previous, next) => {
      return { ...previous, ...decorateQueryResult(next) };
    }, addData)
    : addData;

  useEffect(() => {
    if (data?.query?.operation?.variables) {
      addData = { ...addData, ...data.query.operation.variables };
    }
  }, [data.query]);

  return (template: string | undefined, additionalData: any = {}) =>
    TemplateRegistry.render(template, {
      ...addData,
      ...decorateQueryResult(additionalData),
    });
};
