import type { Elements } from '../config/map/actions';
import { useProcessContext } from '@/process/hooks/common';
import { useStatus } from '@/stores/calculation/statuses/hooks';
import { observer } from 'mobx-react-lite';
import type { ComponentType } from 'react';
import { useThrottledCallback } from 'use-debounce';

type BuilderProps = {
  elementName: Elements;
  valueName: string;
};

export function buildAction<T>(
  Component: ComponentType<T>,
  { elementName, valueName: processName }: BuilderProps
) {
  return observer((props: T) => {
    const status = useStatus(elementName);

    const context = useProcessContext();
    const throttledAction = useThrottledCallback(
      () => {
        import(`process/${processName}/action`).then((module) => module.action(context));
      },
      1200,
      {
        trailing: false,
      }
    );

    return (
      <Component
        onClick={throttledAction}
        status={status}
        disabled={status === 'Disabled'}
        loading={status === 'Loading'}
        {...props}
      />
    );
  });
}
